new關(guān)鍵字生成實例做了啥

20200105.jpg

風(fēng)停在窗邊,囑咐我要熱愛這個世界

function Human (name, age) {
    this.name = name
    this.age = age

    this.say = function () {
        console.log(`my name is ${this.name}, my age is ${this.age}`);
    }
}

Human.prototype.color = 'yellow'
Human.prototype.sayHello = function () {
    console.log('Hello!');
}

let human = new Human('kobe', 25)

console.log(human);

human.sayHello()

console.log('--------------------------');

console.log(human.color);



截圖如下


image.png

根據(jù)上面我們來看一下new都干了啥

  • 初始化新對象
let obj = {}
  • 原型的執(zhí)行,確定實例對象的構(gòu)造函數(shù)
obj._proto_ = Human.prototype
  • 綁定this指向?qū)ο鬄閛bj,傳入?yún)?shù),執(zhí)行Human構(gòu)造函數(shù),進(jìn)行屬性和方法的賦值操作
Human.call(obj, 'kobe', 25)

如果我們不使用new關(guān)鍵字的話,而是直接調(diào)用Human () ,那么此時this指向就是window,而使用了new的話,指向的就是Human本身了

  • 返回該對象
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容