在 JavaScript 中,有几种方式可以创建对象:

1. 使用对象字面量(Object Literal):

const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello!');
  }
};

2. 使用构造函数(Constructor Function):

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log('Hello!');
  };
}

const person = new Person('John', 30);

3. 使用 Object.create 方法:

const personPrototype = {
  greet: function() {
    console.log('Hello!');
  }
};

const person = Object.create(personPrototype);
person.name = 'John';
person.age = 30;

4. 使用 class 语法(ES6):

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log('Hello!');
  }
}

const person = new Person('John', 30);

以上是常见的创建对象的方法。每种方式都有其特点和用途,你可以根据需要选择合适的方式来创建对象。

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.