面向对象基础-重写new

64 阅读1分钟

new 操作符做了什么?

  1. 建立一个空对象
  2. 将构造函数中的this指向这个空对象
  3. 执行构造函数
  4. 返回一个引用对象

写一个自己的new方法

function mynew(ctor, ...params) {
      let obj = {};
      obj.__proto__ = ctor.prototype;
      let result = ctor.call(obj, ...params);
      if (result != null && typeof result == ("object" || "function")) {
        return result;
      }
      return obj;
}
function Dog(name) {
    this.name = name;
}
let dog1 = mynew(Dog, "狗狗");
console.log(dog1 instanceof Dog);//true