我们经常会使用new关键字,那我们在使用new关键字的时候,new到底做了什么呢
- 创建一个空的javascript对象就比如(即{});
- 链接该对象(即设置该对象的构造函数)到另一个对象;
- 将步骤1新创建的对象作为this的上下文;
- 如果该函数有没有返回对象,没有则返回this;
接下来按照这个目标去实现
function _new () {
const obj = {}
const constructor = [].shift.call(arguments)
obj.__proto__ = constructor.prototype
const res = constructor.apply(obj, arguments)
return typeof res === 'object' ? res : obj
}
function F (name, age) {
this.name = name
this.age = age
}
const f1 = _new(F, 'xx', '30')
console.log(f1.name) // xx