JavaScript創建對象的方式有以下幾種:
var obj = {
key1: value1,
key2: value2,
// ...
};
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person("John", 30);
var obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
// ...
var obj = Object.create(proto);
function createPerson(name, age) {
var person = {};
person.name = name;
person.age = age;
return person;
}
var person = createPerson("John", 30);
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
var person = new Person("John", 30);
這些是創建對象的常用方式,每種方式都有其適用的場景和特點。