
在 javascript 中,“new”关键字通过构造函数创建对象的新实例。
新关键字的目的:
- 对象创建。
- 原型链接。
- 绑定“this”并返回新创建的对象。
运作原理:
当您在构造函数中使用 new 关键字时,将执行以下步骤:
- 创建了一个新的空对象。
- 新对象的原型设置为构造函数的原型。
- 构造函数被调用到设置了“this”的新对象。
- 如果构造函数没有返回对象,则返回新创建的对象。
例子 :
这是一个简洁的代码示例,演示了 javascript 中 new 关键字的使用,涵盖了对象创建、原型链接和绑定“this”所涉及的所有基本步骤。
// Step 1: Define a constructor function
function Car(make, model) {
this.make = make; // Step 3: Bind properties to the new object
this.model = model;
}
// Step 4: Add a method to the Car prototype
Car.prototype.getDetails = function() {
return `${this.make} ${this.model}`;
};
// Step 2: Create a new instance of Car using the new keyword
const myCar = new Car('Toyota', 'Corolla');
// Using the method from the prototype
console.log(myCar.getDetails()); // Output: Toyota Corolla
// To demonstrate the prototype linkage
console.log(myCar instanceof Car); // Output: true
概括
综上所述,new 关键字对于 javascript 中的面向对象编程至关重要。它允许创建对象的新实例,建立原型继承,绑定 this 的上下文,并处理创建的对象的返回。了解 new 的工作原理对于在 javascript 中有效使用构造函数和类至关重要。










