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);
这些是创建对象的常用方式,每种方式都有其适用的场景和特点。