手写new函数(直击面试)

146 阅读1分钟
function Person(firtName, lastName) {

​    this.firtName = firtName;

​    this.lastName = lastName;

}

Person.prototype.sayName = function() {

​    console.log(this.firtName)

}

// 函数的new的实例

// const tb = new Person('chen')

// tb.sayName()



// 手写的new函数

func = (obj,...rest) => {

​    // 用传入的对象原型去创建一个空的对象const newObj = Object.create(obj.prototype);

​    // 现在newObj就代表Person,但是this指向没有修改const res = obj.apply(newObj, rest);

​    // 判断传入的obj是否是null或者undefined,我们返回的是newObj,否则返回resreturn typeof res === 'object' ? res : newObj

}

const tb = func(Person, 'chen')

tb.sayName()