2014-11-21 71 views
3

很抱歉的标题,因为我不知道如何定义确切的问题,因为写的...的Chrome DevTools命令行API,jQuery的,美元符号变量

我现在看到的只是问题是在某些特定条件下,加载jQuery后,DevTools Console的美元符号变量($)不会被覆盖。

环境

  • 打开DevTools控制台页面上,其中jQuery加载。
  • 在DevTools Console中运行测试用例。
  • 在每个测试用例之后重新加载页面,以便jQuery被卸载。
  • Chrome版本:37.0.2062.120米

制备代码

function loadJqueryThenFire(func) { 
    if (!window.jQuery) { 
     var s = document.createElement('script'); 
     s.type = 'text/javascript'; 
     s.src = '//code.jquery.com/jquery-1.11.1.js'; 
     s.onload = function() { 
      func(); 
      this.parentNode.removeChild(this); 
     }; 
     document.getElementsByTagName('head')[0].appendChild(s); 
    } else { 
     func(); 
    } 
} 

测试用例1(匿名函数表达式)

test = function() { console.log($); }; 
// this returns Console's "$" object 
loadJqueryThenFire(test); 

测试用例2(命名的函数表达式)

test = function test() { console.log($); }; 
// this returns Console's "$" object 
loadJqueryThenFire(test); 

测试用例3(作为参数传递匿名函数表达式)

// this returns Console's "$" object 
loadJqueryThenFire(function() { console.log($); }); 

测试案例4(作为参数传递命名的函数表达式)

// this returns Console's "$" object 
loadJqueryThenFire(function test() { console.log($); }); 

测试用例5(函数声明)

function test() { console.log($); }; 
// this returns jQuery's "$" object (which is what I am expecting) 
loadJqueryThenFire(test); 

这种行为也发生在了最新的jQuery稳定版本(2.1.1)。

我的问题是:谁能解释为什么$没有被覆盖?这是否与jQuery宣布她的$有关?

编辑:

找到一些更奇特行为...

测试用例6(立即调用的函数表达式)

(function() { 
    function test() { console.log($); }; 
    // this returns Console's "$" object 
    loadJqueryThenFire(test); 
})() 

测试案例7(嵌套函数声明)

function tc7() { 
    function test() { console.log($); }; 
    // this returns jQuery's "$" object (which is what I am expecting) 
    loadJqueryThenFire(test); 
} 
tc7(); 
+1

我认为匿名函数和命名函数需要'$'的值当函数被分配到其中执行函数时的正常功能需要一个变量。 (我很确定这是因为三种函数中变量SCOPE的差异)。当我登录'console.log(window。$)'时,会记录jquery的'$'。 *渴望看到更好的答案* – 2014-11-21 05:10:25

+0

我想这是由于'V8'的代码优化......现在手上没有Firefox来测试其他Javascript引擎。 – cychoi 2014-11-21 05:49:59

回答

0

我没有使用Chrome版本61.0.3163.100,并在所有情况下DevTools控制台$测试是由jQuery的覆盖。

Screenshot