JavaScript中new的实现
过程
- 首先创建了一个新的空对象
- 设置原型,将对象的原型设置为函数的
prototype
对象。 - 让函数的
this
指向这个对象,执行构造函数的代码(为这个新对象添加属性) - 判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。
代码实现
function newPolyfill () {
//创建新对象
let newObject = null,flag
//拿到构造函数
const constructor = Array.prototype.shift.call(arguments)
if(typeof constructor !== 'function') {
console.err('error')
return
}
//把对象的原型设置为函数的prototype对象
newObject = Object.create(constructor.prototype)
//把this指向新的对象,执行函数
const result = constructor.apply(newObject, arguments)
//判断构造函数是否返回引用对象,有则返回这个对象,没有则返回新的对象
flag = result&&(typeof result === 'function' || typeof result === 'object')
return flag ? result : newObject
}
function Foo(name) {
this.name = name
}
Foo.prototype.play = function() {
console.log(this.name + 'playing');
}
const obj = newPolyfill(Foo,'小明')
obj.play()
运行效果
8d2b40f1f1710247be69765cd71adc4d