Possible Duplicate:
how does jquery chaining work?
这是您在 jQuery 代码中看到的正常情况:
$("div.selected").html("Blah.");
所以,在上面的代码中,在函数$()
中,它有一个叫做html()
的函数。我不明白的是,我通常会做的是:
funcA("blah"); //normal function, cool.
funcA.funcB("blah"); //normal function in an object, still cool.
现在这是令人困惑的:
funcA("blah").funcB("blah") //huh??
funcB
如何知道funcA
中的参数?
jQuery 如何实现这一点?
谢谢。
//function returning an object is a possibility. bar has access to elem because of
// the shared scope
function foo ( elem ) {
return {
bar : function () {
return elem.id;
}
};
}
在这一个中,foo
函数返回一个包含您想要的任何方法的对象。所以当你调用 foo
时,你会收到:
{
bar : function () {
return elem.id;
}
}
elem
出现在您对 foo
的调用中。如果您要在 bar
的顶部添加 console.log( elem )
,您会发现它与传递给 foo 的内容相同
。
//this is kinda how jQuery does it:
var foo = (function() {
function foo ( elem ) {
this.elem = elem;
}
foo.prototype.bar = function () {
return this.elem.id;
};
return function ( elem ) {
return new foo( elem );
};
}());
这个稍微复杂一点,实际上分为两部分。
function foo ( elem ) {
this.elem = elem;
}
foo.prototype.bar = function () {
return this.elem.id;
};
谁不喜欢混合了经典继承名称的原型(prototype)继承?无论如何......函数既充当常规函数又充当构造函数。意思是,当使用 new
关键字调用时,会发生两件特殊的事情:
foo
中的 this
指的是 foo.prototype
的新副本
foo.prototype
被返回(除非foo
返回一个对象)
请注意,foo.prototype
不是一个神奇的值。它就像任何其他对象属性一样。
因此,在 foo
函数/构造函数中,我们只是设置 foo.prototype.elem
,而不是直接设置。可以这样想(有点不准确,但可以):foo.prototype
是产品的蓝图。每当你想做更多的时候,你可以使用蓝图——复制里面的东西,传递下去。在 foo
内部,this
指的是蓝图的复制。
但是,通过显式设置 foo.prototype
的值,我们正在改变蓝图本身。每当调用 foo
时,都会使用这个更改后的蓝图调用它。
最后,一旦 foo
完成,复制(复制的蓝图,但在 foo
完成之后)被返回。此复制包含原始蓝图,以及我们可能添加的所有其他内容 - 在本例中为 elem
。
var foo = (function() {
...
return function ( elem ) {
return new foo( elem );
};
}());
我们创建一个无名函数并立即执行它。
(function () {
console.log( 'meep' );
}());
//is the equivalent of:
var something = function () {
console.log( 'meep' );
};
something();
something = undefined; //we can no longer use it
//and of this
function () {
console.log( 'meep' );
}(); //<--notice the parens
//however, it's considered good practice to wrap these self-executing-anonymous-functions
// in parens
与所有其他函数一样,它们可以返回值。这些值可以被捕获到变量中。
var answer = (function () {
return 42;
}());
answer ==== 42;
var counter = (function () {
var c = 0;
return function () {
return c++;
};
}());
//counter is now a function, as a function was returned
counter(); //0
counter(); //1
counter(); //2...
所以:
var foo = (function () {
...
return function ( elem ) {
...
};
}());
返回一个接收参数的函数,该函数现在分配给 foo
。
函数内部:
return new foo( elem );
是为了确保我在上面谈到的特殊条件 - 它通过显式执行 new
操作来确保制造蓝图的新副本。这实际上可以像这样复制:
function foo ( elem ) {
this.elem = elem;
}
foo.prototype.bar = function () {...};
只要您始终使用new
关键字调用foo
。