我刚刚开始学习jQuery和OO Javascript,所以我想弄清楚哪些属于哪个以及他们做了什么。我在JQuery文档中看到了这段代码
(function($sub) {
$sub // a subclass of jQuery
$sub === jQuery; //= false
$sub.fn.myCustomMethod = function(){
return 'just for me';
}
$sub(document).ready(function() {
$sub('body').myCustomMethod(); //= 'just for me'
});
})(jQuery.subclass());
问题:
由于
答案 0 :(得分:5)
(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的所有功能,但是您添加或更改的任何内容都不会影响“global 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
如果需要进一步解释或者您对其他事情感到好奇,请提及它。我可能已经掩饰了一些我认为显而易见的事情。
答案 1 :(得分:2)
答案 2 :(得分:0)
我会尝试解释它
例如:
function dirty($arg) {...}
在全局范围内可见
(function dirty($arg) {...})("some arg");
在全局范围内不可见 - 它创建一个具有自己范围的函数,立即调用它,如果它没有分配给变量,则引用丢失
通过这种方式,您可以在不更改全局jQuery对象的情况下更改jQuery的功能。我不知道这有什么用,但这就是它的作用:) 2.来自jQuery API文档 -
创建jQuery的子类 对象,允许您添加其他内容 或改变jQuery方法和 属性不影响 全球jQuery。