我正在用extend
進行一些測試,在我做了一些觀察後,我有點困惑。第一次觀察:jQuery.extend和jQuery.fn.extend
console.log($.extend === $.fn.extend); // trure
// and since $ === jQuery then ...
console.log(jQuery.extend === jQuery.fn.extend); // true
到目前爲止這麼好,不是嗎?鑑於上述結果我當時以爲,這樣做:
// SNIPPET 1
$.extend({
log: function(m) {
console.log(m);
}
});
這:
// SNIPPET 2
$.fn.extend({
log: function(m) {
console.log(m);
}
});
是一樣非常的事。但事實上,事情的方式非常不同。事實上,如果你運行SNIPPET 1然後執行:
$("body").log("whatever");
你會得到一個錯誤(未定義日誌)。但你可以這麼做:
$.log("whatever");
如果運行,而不是內容片段2你會得到相反的結果,即:
$("body").log("whatever"); // this will work
$.log("whatever"); // this won't
什麼鬼?我很欣賞.extend
擴展了它被執行的對象($
vs $.prototype
),但我沒有得到的是它是如何做到的!特別是考慮到以下事實:
$.extend === $.fn.extend // true
功能是一樣的!它如何產生2個不同的結果?
不同範圍... –