手写New

227 阅读1分钟

要想实现new的话就要先看看new都做了哪些事情

function Obj(){this.name=1};
Obj.prototype.say=function(){console.log(this.name)}
const o = new Obj();
// new操作符做的事情
// 1、创建了一个空对象o={};
// 2、将o.__proto__指向了Obj.prototype
// 3、此时Obj执行的时候将Obj中的this改成了o
// 4、如果Obj本事有返回引用类型的值,那么o就是Obj返回的值否则就是返回的对象
o.say() //1

根据new操作符做的事情就可以实现自己的new方法

function myNew(constr, ...args) {
    //创建一个空对象
    let obj = {};
    //讲obj的__proto__指向构造函数的原型
    obj.__proto__ = constr.prototype;
    // 把构造函数的this执行obj,并且接收构造函数的返回值
    const result = constr.apply(obj, args);
    // 判断result的类型,如果不是引用类型就返回obj否则就返回构造函数的返回值
    return (result !== null && typeof result === "object") ||
        typeof result === "function"
        ? result
        : obj;
    }

测试

function Test(name, age) {
    this.name = name;
    this.age = age;
    return null;
  }
  Test.prototype.say = function() {
    console.log(`我的名字是${this.name},我今年${this.age}岁了`);
  };
  var test = myNew(Test, "Tom", "18");
  test.say();
  console.log(test);
  console.log(test instanceof Test);

  var test2 = new Test("Tom", "18");
  test2.say();
  console.log(test2);
  console.log(test2 instanceof Test);