function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name
}
var a = new Psrson('sven')
console.log(a.name) // 'sven'
console.log(a.getName()) // 'sven'
console.log(Object.getPrototypeOf(a) === Person.prototype) // true

console.log(a)
由上面這個(gè)例子可以知道new在執(zhí)行時(shí)做了哪些事情:
- 創(chuàng)建一個(gè)新對(duì)象
- 將傳入的參數(shù)變?yōu)榱诵聦?duì)象的屬性,這是構(gòu)造函數(shù)內(nèi)部的具體實(shí)現(xiàn)決定的
- 讓新對(duì)象的原型指向構(gòu)造函數(shù)的prototype屬性(構(gòu)造函數(shù)的prototype的constructor屬性默認(rèn)指向構(gòu)造函數(shù)本身)
- 返回一個(gè)對(duì)象
所以根據(jù)上面這幾條,我們可以模擬一下new的實(shí)現(xiàn)過(guò)程:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
var objectFactory = function() {
var obj = new Object(),
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var ret = Constructor.apply(obj, arguments);
return typeof ret === 'object' ? ret : obj;
}
var a = objectFactory(Person, 'sven')
console.log(a.name)
console.log(a.getName())
console.log(Object.getPrototypeOf(a) === Person.prototype)

console.log(a)
可以看出,上下兩個(gè)并沒(méi)有什么區(qū)別