JS new 一个对象的过程

529 阅读1分钟

new 关键字

// 定义构造函数
function Person (name) {
  console.log("constructor");
  // 将构造函数的this指向新对象
  this.name = name;
}
​
// 定义类的属性
Person.prototype.say = function () {
  console.log("My name is", this.name);
};
​
// 创建新对象
const p1 = new Person("tom");
p1.say();
在调用 new 时,主要做了以下4件事情
  1. 创建一个新的空对象

  2. 将空对象的 proto 指向构造函数的 prototype

  3. 执行构造函数,并将空对象的 this 绑定为构造函数的 this

  4. 如果构造函数有返回一个对象,则返回这个对象,否则返回新创建的那个对象

写下 new 的简单实现
function newZn (constructorFn, ...args) {
    // 1.创建一个空对象
    const obj = {};
    // 2.将空对象的 __proto__ 指向构造函数的 prototype
    obj.__proto__ = constructorFn.prototype
    // 3.执行构造函数,并将空对象的 this 绑定为构造函数的 this
    const res = constructor.apply(obj, args);
    // 4.如果构造函数有返回一个对象,则返回这个对象,否则返回新创建的那个对象
    return typeof res==='obj'?res:obj;
}
const p1 = newZn(Person, 'zhangning')
p1.say();