2014-07-17 102 views
-1
Function.prototype.new = function () { 
    // Create a new object that inherits from the 
    // constructor's prototype. 
    var that = Object.create(this.prototype); 
    // Invoke the constructor, binding –this- to 
    // the new object. 
    var other = this.apply(that, arguments); 
    // If its return value isn't an object, 
    // substitute the new object. 
    return (typeof other === 'object' && other) || that; 
}); 

這是來自JavaScript的構造函數實例的一個替代實現:The Good Parts。 我的問題是爲什麼我們需要var other = ... 我們不能只返回變量嗎?用Javascript查看構造函數調用的另一種方法

+0

您可能想要了解'&&'和'||'運算符的用途:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators –

+0

謝謝爲鏈接。它確實有幫助,但它沒有回答我的問題。變量'that'引用新創建的對象。那麼爲什麼還要檢查'other'是什麼類型呢?你可以直接返回'那個'嗎? – Meyyappan

+1

我覺得你大部分都是因爲標題誤導而降低讚譽。你可能想要編輯標題,特別是你問的是什麼 –

回答

1

我們不能只返回變量嗎?

不,因爲這不是new operator做什麼:

如果構造函數沒有明確地返回一個對象,[從樣機繼承]的 對象來代替。 (常 構造函數沒有返回值,但他們可以選擇這樣做,如果 他們要覆蓋正常的對象的創建過程。)

所以,如果調用構造函數返回一個other那是一個對象,我們需要返回它。

請注意,代碼甚至是不正確的,因爲返回的函數也應該視爲對象(但typeof不會爲其產生"object")。你也可以檢查一下,或使用Object(other) === other trick。你也可能想看看Use of .apply() with 'new' operator. Is this possible?的一些答案。

+0

哦,男人,忘了所有關於適用新的伎倆。很好的回答 –

+0

然而,它並沒有真正幫助我們理解「新」功能的細節:-) – Bergi

+1

不,但[此答案](http://stackoverflow.com/a/3658673/5056)確實 –

相關問題