当使用 new 运算符执行一个函数时,称为
构造函数执行模式
,返回一个实例对象,而函数体中的this
指向这个实例
如何实现?
- 创建一个对象
- 将对象原型指向构造函数的原型
- 将this指向这个对象
- 返回这个对象
// 实现 new
function fakeNew(){
const obj = {}
// 获取构造函数
const _constructor = [].shift.call(arguments)
// 改变原型指向
Object.setPrototypeOf(obj, _constructor.prototype)
// 改变this指向
const result = _constructor.apply(obj, arguments)
// 返回对象
return typeof result === 'object' ? result : obj
}
// 例
function Person(name, age) {
this.name = name;
this.age = age
}
const person1 = new Person('Kevin', 28)
const person2 = fakeNew(Person, 'Jhon', 29)
融会贯通
function Fn(n) {
let m = 10;
this.total = n + m;
this.say = function() {
console.log(this.total)
}
}
const f1 = new Fn(10)
const f2 = new Fn(20)
const f3 = new Fn // new 不管是否加(),都相当于执行函数,只是没有参数
console.log(f1.m) // undefined 私有变量和实例没有关系
console.log(f2.n) // undefined 私有变量和实例没有关系
f2.say() // 30 此时 this 指向f2
console.log(f1 === f2) // false
console.log(f3) // Fn {total: NaN, say: ƒ}