js 实现一个new
实现 new 操作符的功能
在 JavaScript 中,new 操作符用于创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。以下是手动实现 new 功能的步骤:
实现步骤
-
创建一个空对象
使用Object.create()方法创建一个新对象,并将其原型指向构造函数的原型对象。const obj = Object.create(constructor.prototype); -
调用构造函数并绑定
this
将构造函数的作用域赋给新对象(即this指向新对象),并执行构造函数。const result = constructor.apply(obj, args);
-
处理返回值
如果构造函数返回一个对象,则返回该对象;否则返回新创建的对象。return result instanceof Object ? result : obj;
完整代码实现
function myNew(constructor, ...args) {
// 1. 创建一个空对象,并继承构造函数的原型
const obj = Object.create(constructor.prototype);
// 2. 执行构造函数,绑定 this 到新对象
const result = constructor.apply(obj, args);
// 3. 如果构造函数返回对象则返回该对象,否则返回新对象
return result instanceof Object ? result : obj;
}
使用示例
function Person(name, age) {
this.name = name;
this.age = age;
}
// 使用原生 new
const p1 = new Person("Alice", 25);
console.log(p1.name); // "Alice"
// 使用自定义 myNew
const p2 = myNew(Person, "Bob", 30);
console.log(p2.age); // 30
关键点说明
-
原型链继承
Object.create(constructor.prototype)确保新对象继承构造函数的原型方法。
-
构造函数返回值处理
如果构造函数显式返回对象(如return { custom: 1 }),则优先返回该对象;否则返回新创建的obj。 -
与原生
new的对比
手动实现的myNew模拟了原生new的核心逻辑,包括原型链绑定、this绑定和返回值处理。






