Skip to content

手写new

js
function myNew(Constructor, ...args) {
    // 1. 创建一个新的空对象
    const obj = {};
    
    // 2. 将这个新对象的 __proto__ 属性链接到构造函数的 prototype 对象
    obj.__proto__ = Constructor.prototype;

	// 使用 Object.create 创建新对象,并设置其原型为构造函数的 prototype
    // const obj = Object.create(constructor.prototype);  
    
    // 3. 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象)
    // 使用 Function.prototype.call 或者 Function.prototype.apply 来调用构造函数
    const result = Constructor.apply(obj, args);
    
    // 4. 如果构造函数返回了一个对象,则使用它;否则返回新创建的对象
    return result instanceof Object ? result : obj;
}

// 使用示例:
function MyObject(name) {
    this.name = name;
}

MyObject.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}!`);
};

// 使用手写的 myNew 来创建 MyObject 的实例
const myObj = myNew(MyObject, 'Alice');
myObj.greet(); // 输出: Hello, my name is Alice!