the*_*ist 7 javascript javascript-framework
我看到很多函数返回的不是结果而是函数.下面的示例显示函数getWindow返回函数.为什么它不能只返回变量"赢"?当我返回结果和功能时?谢谢.
var A = function(){};
A.prototype=
{
getWindow : function()
{
var win = new B.window();
return (
this.getWindow = function()
{
return win;
})();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码与您的代码等效,但更容易理解:
A.prototype = {
getWindow: function() {
var win = new B.window();
this.getWindow = function() {
return win;
};
return win;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
首先创建一个A实例:
var a = new A();
Run Code Online (Sandbox Code Playgroud)
然后,调用getWindow该实例:
a.getWindow();
Run Code Online (Sandbox Code Playgroud)
这里,调用了getWindow的方法A.prototype。正如您在上面的代码中看到的,A.prototype.getWindow将创建 anew B.window()并返回它,但是在两者之间,它还会在实例对象本身上getWindow创建一个方法。
现在,如果您getWindow再次致电:
a.getWindow();
Run Code Online (Sandbox Code Playgroud)
A.prototype.getWindow 不再被调用,因为实例对象本身有getWindow方法。getWindow此方法返回与第一次调用该方法时返回的相同“win”对象。
您的模式允许多个A实例使用相同的A.prototype.getWindow方法来实例化它们自己的“win”对象。考虑一下:
var a1 = new A,
a2 = new A,
a3 = new A;
a1.getWindow(); // creates window W1 and returns it
a2.getWindow(); // creates window W2 and returns it
a1.getWindow(); // returns window W1
a2.getWindow(); // returns window W2
a3.getWindow(); // creates window W3 and returns it
a1.getWindow(); // returns window W1
a2.getWindow(); // returns window W2
a3.getWindow(); // returns window W3
Run Code Online (Sandbox Code Playgroud)
这是一个非常有用的模式:)
更新:
这是你的代码:
return (this.getWindow = function() {
return win;
})();
Run Code Online (Sandbox Code Playgroud)
首先,我们看一下括号内的表达式:
this.getWindow = function() { return win; }
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,这是一个赋值表达式。匿名函数对象被分配给(实例对象) getWindow引用的对象的属性。this
请注意,此函数返回win对象。
这个赋值表达式的结果就是函数对象本身!这意味着括号内的值是函数对象。
现在,让我们看一下整个情况:
return ( the_function_object )();
Run Code Online (Sandbox Code Playgroud)
我们可以删除括号,因为我们不再需要它们:
return the_function_object();
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,函数对象被调用,然后返回该函数的返回值。
如上所述,该函数返回win。因此,代码解析为:
return win;
Run Code Online (Sandbox Code Playgroud)
所以你的代码的作用是:
首先,它分配function() { return win; }给this.getWindow.
其次,它返回调用该函数的结果win。
我的代码产生相同的结果,但更容易理解:
this.getWindow = function() {
return win;
};
return win;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |