手写一个new

53 阅读1分钟
function Car(mark, model, year) {
    this.mark = mark;
    this.model = model;
    this.year = year;
}

const car1 = new Car('mark', 'model', 2021)
console.log("car1", car1)

// new的过程发生了什么?
// 1.创建一个空对象
// 2.指定原型链
// 3.更改this指向
// 4.返回值
function myNew(Fun, ...ages) {
    let obj = {}
    obj.__proto__ = Fun.prototype //将obj的原型链指向构造函数的prototype
    Fun.apply(obj, ages) //将构造函数内部的this绑定到obj上,并执行构造函数
    return obj
}

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.sayName = function () {
    console.log('sayName', this.name)
}

const apple = myNew(Person, 'apple', 18)
apple.sayName() //apple
console.log('apple', apple)

image.png