new
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一
new实现了哪些功能
举个栗子:
function Baby(name, age) {
this.name = name
this.age = age
}
Baby.prototype.height = 88
Baby.prototype.getHeight = function() {
console.log(`${this.name} heiht ${this.height}.`)
}
let baby = new Baby('George', 1) // new
baby.name // George
baby.age // 1
baby.height // 88
baby.getHeight() // George height 88.
Baby.prototype.__proto__ === Object.prototype // true
我们可以看到,实例baby可以
- 访问构造函数里的属性
- 访问构造函数原型上的属性和方法
实现模拟
由于new是关键字,我们预设如下:
let baby = simulateNew(Baby, 'George', 1, 50)
simulateNew函数第一个参数是构造函数,后面是对应的参数值,需要返回一个baby对象,这个对象可以实现诸如效果:
* baby.name === George
* baby.age === 1
* baby.height === 88
* baby.getHeight() // George height 88.
* Baby.prototype.__proto__ === Object.prototype
ok ,我们来尝试一下。
// simulate new
function Baby(name, age, height) {
this.name = name
this.age = age
}
Baby.prototype.height = 88
Baby.prototype.getHeight = function() {
console.log(`${this.name} heiht ${this.height}.`)
}
function simulateNew(constructorFun, ...args) {
let instance = {} // 实例
constructorFun.apply(instance, args) // 调用构造函数
// 获取原型链上方法、属性
instance.__proto__ = constructorFun.prototype
constructorFun.prototype.__proto__ = Object.prototype
return instance
}
let baby = simulateNew(Baby, 'George', 1, 50)
验证一下:
baby // {name: "George", age: 1}
baby.height // 88
baby.getHeight() // George heiht 88.
Baby.prototype.__proto__ === Object.prototype // true
嗯,没毛病。