(1)自調用函數
function() {
}();
都對自己無效的,因爲它們會導致語法錯誤,它的混亂看到它調用的底部。
這就是爲什麼JavaScript社區在自調用函數啓動時使用(
讓其他代碼讀者意識到它不是一個正常函數。
var o = (function() {
})();
每當我看到有(
啓動功能,我知道,這是自調用。這意味着它立即執行並且o
包含函數的返回值而不是函數。
(2)的jQuery子類
警惕,使用子類依賴於具有jQuery的1.5。我建議你等待官方發佈,而不是使用1.5 RC1,因爲有一些問題需要解決。
jQuery.subclass
是jQuery 1.5 beta的一部分。這是jQuery的一個新功能,它實質上構成了jQuery的一個子類。
這意味着您添加到jQuery.subclass的任何內容都不會添加到jQuery中。這個jQuery子類有jQuery的所有功能,但任何您添加或更改不會影響「全球jQuery的」
註釋樣品來源
// self invoking function. This creates a closure so that anything declared in
// this function is local and doesn't effect global state
(function($sub) {
$sub // a subclass of jQuery
$sub === jQuery; //= false
// here we extend $.fn with a new method. This actually extends the prototype of $sub
// $sub.fn === $sub.prototype === $()
// $sub.fn is actually a new jQuery object. This means that when using $sub we first look
// for method defined on $sub.fn, and if there aren't any we look on methods defined
// on $.fn. A useful feature of this is that you can overwrite methods
$sub.fn.myCustomMethod = function(){
return 'just for me';
}
// We can "overwrite" methods of jQuery by hiding the original methods.
$sub.fn.attr = function() {
alert("new attr!");
// you can go into $sub.superclass to get the original $ object and call methods there
$sub.superclass.attr.apply(this, arguments);
}
// This calls .ready from the original jQuery
$sub(document).ready(function() {
$sub('body').myCustomMethod(); //= 'just for me'
});
// we pass in a subclass of jquery at the bottom. This means that $sub has all the
// functionality of $ but doesn't change $ itself.
})(jQuery.subclass());
免責聲明.__proto__
是棄用和壞。它僅用於說明jQuery.subclass原型鏈的外觀。
對於那些誰瞭解.__proto__
(此獲取對象的構造函數的原型)
var $sub = jQuery.subclass();
$sub.__proto__ === $sub.fn; // true
$sub.__proto__.__proto__ === $.fn; // true
// example of .__proto__
function constructor() { }
var o = new constructor;
o.__proto__ === constructor.prototype; // true
如果需要進一步的解釋,或者如果您想了解什麼都請不要客氣。我可能會掩飾一些我認爲很明顯的東西。
@Goleztroll technolally該表達式返回調用後自外部括號結束後調用的函數的值。 – Raynos 2011-01-29 23:29:05
不,它不。只有函數聲明包含在括號中。括號在函數的關閉`}`之後關閉。 – GolezTrol 2011-01-29 23:33:21