
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本身了
- 返回該對象