前端面试js系列:手写new

150 阅读1分钟

在JavaScript中,new关键字用于创建一个用户定义的对象类型的实例,或者调用一个构造函数。具体步骤分为:

  • 先创建一个空对象{}
  • 将这个新对象的原型设置为构造函数的prototype属性
  • 调用构造函数,并将新对象作为this的上下文传递进去。
  • 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象。

以上操作换成代码实现就比如:

function myNew(Constructor, ...args) {
    // 1. 创建一个空对象
    const newInstance = {};

    // 2. 将新对象的原型设置为构造函数的 prototype 属性
    newInstance.__proto__ = Constructor.prototype; // 或者使用 Object.setPrototypeOf(newInstance, Constructor.prototype);

    // 3. 调用构造函数,并将新对象作为 this 的上下文传递进去
    const result = Constructor.apply(newInstance, args);

    // 4. 检查构造函数的返回值,如果没有返回其他对象,则返回新对象
    return typeof result === 'object' && result !== null ? result : newInstance;
}

我们来实现一下这个操作:

 function myNew(Constructor, ...args) {
    // 1. 创建一个空对象
    const newInstance = {};

    // 2. 将新对象的原型设置为构造函数的 prototype 属性
    newInstance.__proto__ = Constructor.prototype; // 或者使用 Object.setPrototypeOf(newInstance, Constructor.prototype);

    // 3. 调用构造函数,并将新对象作为 this 的上下文传递进去
    const result = Constructor.apply(newInstance, args);

    // 4. 检查构造函数的返回值,如果没有返回其他对象,则返回新对象
    return typeof result === 'object' && result !== null ? result : newInstance;
}
function Person(name) {
    this.name = name;
    this.greet = function() {
        console.log(`Hello, my name is ${this.name}.`);
    };
}
const person = myNew(Person, 'Alice');
person.greet(); // 输出: Hello, my name is Alice

输出结果为:

image.png