2016-01-21 69 views
1

最近,我讀了MDN documentation on the new operator,我被它用來做什麼的簡潔描述來襲:是否有可能在JS中重新創建「新」運算符?

當執行代碼新(...),下面的事情發生:

  1. 創建一個新對象,繼承自Foo.prototype。
  2. 構造函數Foo被調用指定的參數,並綁定到新創建的對象。 new Foo相當於 new Foo(),即如果沒有指定參數列表,Foo被稱爲 沒有參數。
  3. 構造函數返回的對象成爲整個新表達式的結果。如果構造函數不顯式返回對象,則使用步驟1中創建的對象代替 。 (通常構造函數不返回值,但可以 選擇這樣做,如果他們想覆蓋正常的對象創建 過程。)

好像沒有這些東西都是特權操作,那麼是否有可能用其他語言結構完全重新創建new的動作?

請注意,我不計數Reflect.construct,因爲它的定義是「它像新函數一樣起作用」。

+1

公告自ES6以來,你必須使用'Reflect.construct',上面的描述來自ES5,一些內建函數和使用'class'語法*定義的構造函數區分被調用爲構造函數和被調用的方法 – Bergi

回答

1

此功能非常再現Reflect.construct,從而new(與construct的最後一個參數之外,使用new操作時沒有等價的:

function fauxNew (constructor, args) { 

    // allocate a new object and set the prototype 
    var newObject = Object.create(constructor.prototype) 

    // call the constructor with "this" bound to the new object 
    var retVal = constructor.apply(newObject, args || []) 

    // if the constructor returned an object, return it; 
    // otherwise return the new object 
    var constructorReturnedAnObject = 
     !!retVal && ["object", "function"].indexOf(typeof retVal) !== -1 
    return constructorReturnedAnObject? retVal : newObject 
} 

這裏是the same code presented alongside some test cases

+1

不要相信檢測對象時檢測'typeof'。它可能會爲不可召回的非標準外來物體返回奇怪的東西,例如, ' 「未知」'。 Object(retVal)=== retVal'更可靠。 – Oriol

相關問題