[英]When function returns result and when function in JavaScript
我看到很多函數返回的不是結果而是函數。 下面的示例顯示函數getWindow返回函數。 為什么它不能只返回變量“贏”? 當我返回結果和功能時? 謝謝。
var A = function(){};
A.prototype=
{
getWindow : function()
{
var win = new B.window();
return (
this.getWindow = function()
{
return win;
})();
}
}
此代碼等同於您的代碼,但更容易理解:
A.prototype = {
getWindow: function() {
var win = new B.window();
this.getWindow = function() {
return win;
};
return win;
}
}
用法:
首先,創建一個A實例:
var a = new A();
然后,在該實例上調用getWindow
:
a.getWindow();
這里,調用A.prototype
的getWindow
方法。 正如您在上面的代碼中看到的, A.prototype.getWindow
將創建一個new B.window()
並返回它 ,但是在它們之間,它還將在實例對象本身上創建一個getWindow
方法。
現在,如果再次調用getWindow
:
a.getWindow();
不再調用 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
這是一個非常有用的模式:)
更新:
這是你的代碼:
return (this.getWindow = function() {
return win;
})();
首先,讓我們看一下parens中的表達式:
this.getWindow = function() { return win; }
如您所見,它是一個賦值表達式。 將匿名函數對象分配給this
(實例對象)引用的對象的getWindow
屬性。
請注意,此函數返回win
對象。
這個賦值表達式的結果就是函數對象本身! 這意味着parens中的值是函數對象。
現在,我們來看看整個畫面:
return ( the_function_object )();
我們可以刪除parens,因為我們不再需要它們了:
return the_function_object();
如您所見,調用函數對象, 然后返回該函數的返回值。
如上所述,該函數返回win
。 因此,代碼解析為:
return win;
那么你的代碼所做的是:
首先,它指定function() { return win; }
function() { return win; }
到this.getWindow
。
SECOND,它返回調用該函數的結果,即win
。
我的代碼產生相同的結果,但更容易理解:
this.getWindow = function() {
return win;
};
return win;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.