new運算符用于創(chuàng)建一個用戶定義的對象類型的實例或具有構(gòu)造函數(shù)的內(nèi)置對象的實例。
var foo = new Foo();
以上文為例,使用new進行構(gòu)造調(diào)用會發(fā)生:
- 一個繼承自Foo.prototype得新對象被創(chuàng)建。如:
var obj = new Object();
obj.__proto__ = Foo.prototype;
使用指定的參數(shù)調(diào)用構(gòu)造函數(shù),并將this綁定到新創(chuàng)建的對象。
如果構(gòu)造函數(shù)沒有顯式返回對象,則使用步驟1創(chuàng)建的對象為結(jié)果。否則,構(gòu)造函數(shù)返回的對象作為new表達式的結(jié)果。
根據(jù)這三個步驟,可以模擬實現(xiàn)new以理解。由于不能實現(xiàn)一個運算符,只能用函數(shù)模擬,newObj函數(shù)第一個參數(shù)為構(gòu)造函數(shù),其余參數(shù)為傳入構(gòu)造函數(shù)的值。
function newObj(){
var Constructor = Array.prototype.shift.apply(arguments);
//分離構(gòu)造函數(shù)和參數(shù)
var obj = Object.create(Constructor.prototype);
//步驟1:創(chuàng)建一個繼承自函數(shù)原型實例的對象 此時obj.__proto__ 為 Constructor.prototype
var result = Constructor.apply(obj, arguments);
//步驟2: 使用指定的參數(shù)調(diào)用構(gòu)造函數(shù),并將this綁定到新創(chuàng)建的對象
return typeof result === 'object' ? result || object : object;
//步驟3:如果構(gòu)造函數(shù)沒有顯式返回對象,則使用步驟1創(chuàng)建的對象為結(jié)果。否則,構(gòu)造函數(shù)返回的對象作為new表達式的結(jié)果
//result || object 是因為 typeof null 的結(jié)果也是 'object'
}