js方法实现new
实现 new 操作符的原理
在 JavaScript 中,new 操作符用于创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。手动实现 new 操作符需要模拟其核心行为。
核心步骤
创建一个新的空对象,并将其原型指向构造函数的 prototype 属性。调用构造函数,并将 this 绑定到新创建的对象。根据构造函数的返回值类型决定最终返回结果。
function myNew(constructor, ...args) {
// 创建一个新对象,继承构造函数的 prototype 属性
const obj = Object.create(constructor.prototype);
// 调用构造函数,绑定 this 到新对象
const result = constructor.apply(obj, args);
// 如果构造函数返回对象则返回该对象,否则返回新对象
return result instanceof Object ? result : obj;
}
使用示例
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
// 使用原生 new
const p1 = new Person('Alice', 25);
p1.sayHello(); // 输出: Hello, my name is Alice
// 使用自定义实现
const p2 = myNew(Person, 'Bob', 30);
p2.sayHello(); // 输出: Hello, my name is Bob
处理构造函数返回值
如果构造函数有返回值且返回值是对象,则 new 操作符会返回该对象而非新创建的对象实例。
function Car(model) {
this.model = model;
return { custom: 'return value' };
}
const c1 = new Car('Tesla');
console.log(c1); // 输出: { custom: 'return value' }
const c2 = myNew(Car, 'BMW');
console.log(c2); // 输出: { custom: 'return value' }
边界情况处理
对于基本类型的返回值,new 操作符会忽略并返回新创建的对象实例。

function Bike() {
return 'string value';
}
const b1 = new Bike();
console.log(b1 instanceof Bike); // true
const b2 = myNew(Bike);
console.log(b2 instanceof Bike); // true






