在 JavaScript 中,构造器函数和 new
操作符用于创建多个相似对象的实例,这是实现面向对象编程的重要方式之一。
构造器函数(Constructor Function)是用于创建对象的常规函数,但有两个约定:
new
操作符执行function User(name) {
this.name = name;
this.isAdmin = false;
}
let user = new User("Jack");
console.log(user.name); // Jack
console.log(user.isAdmin); // false
new
操作符的工作原理当使用 new
调用函数时,会发生以下步骤:
{}
[[Prototype]]
(即 __proto__
)链接到构造函数的 prototype
属性this
绑定到这个新对象this
添加属性)通常构造器没有 return
语句,但如果存在:
new
返回该对象而不是 this
function BigUser() {
this.name = "John";
return { name: "Godzilla" }; // 返回这个对象
}
console.log(new BigUser().name); // Godzilla
function SmallUser() {
this.name = "John";
return 1; // 被忽略
}
console.log(new SmallUser().name); // John
new
调用可以使用 new.target
属性来检查函数是否通过 new
调用:
function User() {
if (!new.target) {
throw new Error("必须使用 new 调用!");
}
// 或者强制使用 new
// if (!new.target) {
// return new User();
// }
}
User(); // 报错
new User(); // 正常
可以在构造器中添加方法:
function User(name) {
this.name = name;
this.sayHi = function() {
console.log("My name is: " + this.name);
};
}
let john = new User("John");
john.sayHi(); // My name is: John
除了构造器模式,还可以使用工厂函数创建对象:
function createUser(name) {
return {
name,
isAdmin: false
};
}
let user = createUser("Jack");
区别:
new
,显式返回对象this
指向新对象new
调用构造器class User {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
let user = new User("John");
user.sayHi();
构造器函数和 new
操作符是 JavaScript 原型继承的基础,理解它们的工作原理对于掌握 JavaScript 面向对象编程至关重要。