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();
我認爲匿名函數和命名函數需要'$'的值當函數被分配到其中執行函數時的正常功能需要一個變量。 (我很確定這是因爲三種函數中變量SCOPE的差異)。當我登錄'console.log(window。$)'時,會記錄jquery的'$'。 *渴望看到更好的答案* – 2014-11-21 05:10:25
我想這是由於'V8'的代碼優化......現在手上沒有Firefox來測試其他Javascript引擎。 – cychoi 2014-11-21 05:49:59