function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.sayName = function() {
return this.name;
}
}
let per = new Person("sean", 26, "man");
console.log(per.name);
new 操作做了什么?
- 創(chuàng)建一個(gè)空對(duì)象。
- 將空對(duì)象的proto指向構(gòu)造函數(shù)的原型。
- 將構(gòu)造函數(shù)的this對(duì)象指向新對(duì)象,這樣新對(duì)象就可以訪問構(gòu)造函數(shù)中的屬性和方法。
- 如果構(gòu)造返回值是一個(gè)對(duì)象就返回該對(duì)象,否則返回新對(duì)象。
手動(dòng)實(shí)現(xiàn)new
function newObj() {
let obj = Object.create(null); //1.創(chuàng)建一個(gè)空對(duì)象
let constructor = Array.prototype.shift.call(arguments); //獲取構(gòu)造函數(shù)
obj.__proto__ = constructor.prototype; //2.將空對(duì)象的__proto__指向構(gòu)造函數(shù)的原型
let ret = constructor.apply(obj, arguments);//執(zhí)行構(gòu)造函數(shù)
return typeof ret == 'object' ? ret : obj;//3.返回
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。