【发布时间】:2015-01-19 04:14:34
【问题描述】:
对不起标题,因为我不知道如何定义写作时的确切问题......
我刚才看到的问题是,在某些特定条件下,来自 DevTools 控制台的美元符号变量 ($) 在 jQuery 加载后没有被覆盖。
环境:
- 在加载了
jQuery未的页面上打开 DevTools 控制台。 - 在 DevTools 控制台中运行测试用例。
- 在每个测试用例之后重新加载页面,以便卸载
jQuery。 - Chrome 版本:37.0.2062.120 m
准备代码:
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();
【问题讨论】:
-
我认为匿名函数和命名函数在将函数分配给执行函数时普通函数使用的变量时采用
$的值。 (我很确定这是因为三种函数中变量 SCOPE 的差异。)。 jquery的$在我登录console.log(window.$)时被记录。 渴望看到更好的答案 -
我猜是因为
V8的代码优化......现在手头没有Firefox来测试其他Javascript引擎。
标签: javascript jquery google-chrome-devtools