new的使用方法是 var a = new 構(gòu)造函數(shù)劳淆,a就是這個構(gòu)造函數(shù)的一個實(shí)例。
放上一張?jiān)玩湹膱D
image.png
因此需要這個實(shí)例a.proto =構(gòu)造函數(shù).prototype
而我們知道括勺,a是一個對象曲掰,創(chuàng)建對象的幾種方法中,有一種是Object.create.
var o = Object.create(P)
等同于
o.__proto__ === P//true
因此如何創(chuàng)建a呢乱豆,就是
var o = Object.create(func.prototype);
new運(yùn)算符的步驟
第一步:
一個新的對象被創(chuàng)建宛裕。它是繼承構(gòu)造函數(shù)的原型對象
第二步:
構(gòu)造函數(shù)被執(zhí)行。執(zhí)行的時候揩尸,相應(yīng)的傳參會被傳入,同時上下文會被指定為這個新的實(shí)例错负。
第三步:
如果這個構(gòu)造函數(shù)返回了一個對象勇边,那么這個對象就是實(shí)例的結(jié)果,也就是我們的a识颊,如果沒有返回對象的怀浆,你們new處理的結(jié)果為步驟1創(chuàng)建的對象怕享。
因此實(shí)現(xiàn)代碼:
function New(func) {
// 創(chuàng)建一個空對象,繼承構(gòu)造函數(shù)的原型對象
var res = Object.create(func.prototype);
// 執(zhí)行構(gòu)造函數(shù)沙合,傳遞上下文和參數(shù)
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if (typeof ret === 'object' && ret !== null) {
return ret
} else {
return res
}
}
//測試代碼:
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
alert(this.name);
};
}
var p1 = New(Person, "Ysir", 24, "stu");
console.log(p1)
var a = New(Array)
console.log(a)