Skip to content

new操作符的过程

参考文章:JS new的过程

  1. 创建一个对象
  2. 设置该对象的__proto__属性为构造函数的原型对象
  3. 修改构造函数内部this指针指向新创建的对象
  4. 如果构造函数内部返回引用数据类型则返回构造函数中返回值,否则返回新的对象
javascript
function myNew(fn) {
    // 通过Object.create()创建新的对象并为新的对象设置__proto__属性为构造函数原型空间
    const newObj = Object.create(fn.prototype);
    // 获取传入函数中参数
    const args = [].slice.call(arguments, 1);
    // 修改构造函数的this指针为新创建的对象,
    const res = fn.apply(newObj, args);
    // 判断返回的结果是否为引用数据类型,
    if (
        (typeof res === "object" && res !== null) ||
        typeof res === "function"
    ) {
        return res;
    }
    return newObj;
}
function Student(name, age) {
    this.myName = name;
    this.age = age;
}
myNew(Student, "lmh", 20);
function myNew(fn) {
    // 通过Object.create()创建新的对象并为新的对象设置__proto__属性为构造函数原型空间
    const newObj = Object.create(fn.prototype);
    // 获取传入函数中参数
    const args = [].slice.call(arguments, 1);
    // 修改构造函数的this指针为新创建的对象,
    const res = fn.apply(newObj, args);
    // 判断返回的结果是否为引用数据类型,
    if (
        (typeof res === "object" && res !== null) ||
        typeof res === "function"
    ) {
        return res;
    }
    return newObj;
}
function Student(name, age) {
    this.myName = name;
    this.age = age;
}
myNew(Student, "lmh", 20);