(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