js new 的实现
new 的实现原理
在 JavaScript 中,new 运算符用于创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。其实现原理可以分为以下几个步骤:
-
创建一个新对象
新对象的__proto__属性会被设置为构造函数的prototype对象。 -
绑定构造函数的作用域
构造函数内部的this会被绑定到新创建的对象上。 -
执行构造函数
构造函数内部的代码会被执行,通常用于初始化对象的属性或方法。 -
返回新对象
如果构造函数没有显式返回一个对象,则默认返回新创建的对象。如果构造函数返回了一个对象,则该对象会被作为new表达式的结果。
手动实现 new
以下是一个手动实现 new 功能的函数 myNew:
function myNew(constructor, ...args) {
// 创建一个新对象,并将其原型指向构造函数的 prototype
const obj = Object.create(constructor.prototype);
// 调用构造函数,并将 this 绑定到新对象
const result = constructor.apply(obj, args);
// 如果构造函数返回了一个对象,则返回该对象;否则返回新创建的对象
return typeof result === 'object' && result !== null ? result : obj;
}
使用示例
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
// 使用原生的 new
const person1 = new Person('Alice', 25);
person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
// 使用手动实现的 myNew
const person2 = myNew(Person, 'Bob', 30);
person2.greet(); // 输出: Hello, my name is Bob and I am 30 years old.
关键点说明
-
Object.create
用于创建一个新对象,并将其__proto__指向构造函数的prototype,实现原型继承。 -
apply
将构造函数的this绑定到新对象,并传入参数执行构造函数。 -
返回值处理
如果构造函数返回了一个对象(非原始值),则直接返回该对象;否则返回新创建的对象。
注意事项
- 如果构造函数返回的是原始值(如
number、string、boolean等),new仍然会返回新创建的对象,忽略返回值。 - 手动实现的
myNew函数模拟了原生new的行为,但在实际开发中应直接使用new运算符。






