Javascript:手写new

232 阅读1分钟

new关键字的作用

创建一个用户定义的对象类型实例或具有构造函数的内置对象实例

new执行步骤

1、创建一个新对象
2、链接该对象到另一个对象(即设置该对象的构造函数)
3、将this指向这个新对象
4、如果构造函数返回非空对象,则返回该对象,否则返回刚创建的新对象

根据执行步骤手写new

//带参数
function _new(Fn, ...args) {
  // 创建一个空对象
  const o = new Object();
  // 链接到原型
  o.__proto__ = Fn.prototype;
  // 使用apply绑定this值,将构造函数中的this指向新对象
  const res = Fn.apply(o, args);
  // 如果返回值是一个对象就返回该对象,否则返回构造函数的一个实例对象
  return res instanceof Object ? res : o;
}


//不带参数
function _new() {
  const o = new Object(),
    // 获得构造函数,arguments中去除第一个参数
    Con = [].shift.call(arguments);
  o.__proto__ = Con.prototype;
  const res = Con.apply(o, arguments);
  return res instanceof Object ? res : o;
}


// 不带参数用Object.create创建对象
function _new() {
  const con = [].shift.call(arguments),
    // 用当前对象的原型去创建一个空的对象
    o = Object.create(con.prototype),
    res = con.apply(o, arguments);
  return res instanceof Object ? res : o;
}

执行结果

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayHi = function() {
    console.log(`Hi ${this.name}, I'm ${this.age}`, );
}

let person = _new(Person, 'ccc', 21);
person.sayHi();  // 结果  Hi ccc, I'm 21

使用new关键字

let person = new Person('ccc', 21);
person.sayHi();  // 结果  Hi ccc, I'm 21