JS的8种创建对象的方法
JavaScript 中创建对象的方法有很多种,以下是其中的8种常见方法:
- 使用对象字面量:
let obj = {}; // 创建一个空对象
obj.name = 'John';
obj.age = 30;
- 使用
new
关键字:
let obj = new Object(); // 创建一个空对象
obj.name = 'John';
obj.age = 30;
- 工厂模式:
function createPerson(name, age) {
let obj = new Object();
obj.name = name;
obj.age = age;
return obj;
}
let person = createPerson('John', 30);
- 构造函数模式:
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person('John', 30);
- 原型模式:
function Person() {}
Person.prototype.name = 'John';
Person.prototype.age = 30;
let person = new Person();
- 组合使用构造函数和原型模式(常用):
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
let person = new Person('John', 30);
- 动态原型模式:
function Person(name, age) {
this.name = name;
this.age = age;
if (typeof this.greet !== 'function') {
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
}
}
let person = new Person('John', 30);
- 类(ES6+):
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
let person = new Person('John', 30);
这些方法可以根据你的具体需求和环境选择合适的方式来创建对象。
评论已关闭