【干货】模拟js的new

136 阅读1分钟

A、过程

  1. 创建一个新对象;

  2. 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象); obj.__proto__ = P.prototype;

  3. 执行构造函数中的代码(为这个新对象添加属性);

  4. 返回新对象。

  • 注意:若构造函数中返回this或返回值是基本类型(number、string、boolean、null、undefined)的值,则返回新实例对象;若返回值是引用类型的值,则实际返回值为这个引用类型。

B、代码

/*
 * @Author: laifeipeng 
 * @Date: 2019-02-22 14:07:42 
 * @Last Modified by: laifeipeng
 * @Last Modified time: 2019-02-22 14:13:37
 */
 const New = function (P, ...arg) {
  const obj = {};
  obj.__proto__ = P.prototype;
  const rst = P.apply(obj, arg);
  return rst instanceof Object ? rst : obj;
}
// 极简写法
function New2(fn, ...arg) {
  const obj = Object.create(fn.prototype);
  const rst = fn.apply(obj, arg);
  return rst instanceof Object ? rst : obj;
}

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

const p1 = New(Person, "Ysir", 10, "A");
const p2 = New(Person, "Sun", 20, "B");
console.log(p1.name);//Ysir
console.log(p2.name);//Sun
console.log(p1.__proto__ === p2.__proto__);//true
console.log(p1.__proto__ === Person.prototype);//true

// 与原生js的new对比
const p = new Person('laifeipeng', 20, "C");
console.log(p.name);//laifeipeng
console.log(p.__proto__ === p1.__proto__);//true
console.log(p.__proto__ === Person.prototype);//true

console.log(Person.prototype.constructor === Person);//true

// 结论--正确!

3、图解new及原型链

1