JavaScript 中定义方法的方法有:直接在对象中定义方法使用 class 定义方法使用原型定义方法

如何在 JavaScript 中定义方法
直接在对象中定义方法
最简单的方法是在对象中直接定义方法:
const person = {
name: "John",
greet: function () {
console.log(`Hi, my name is ${this.name}!`);
},
};
person.greet(); // Hi, my name is John!使用 class 定义方法
使用 class 关键字定义类时,可以在类中定义方法:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, my name is ${this.name}!`);
}
}
const person = new Person("John");
person.greet(); // Hi, my name is John!使用原型定义方法
可以通过向原型对象添加方法来定义方法,所有基于该原型的对象都将继承该方法:
const proto = {
greet() {
console.log(`Hi, my name is ${this.name}!`);
},
};
const person1 = Object.create(proto, {
name: {
value: "John",
enumerable: true,
},
});
const person2 = Object.create(proto, {
name: {
value: "Jane",
enumerable: true,
},
});
person1.greet(); // Hi, my name is John!
person2.greet(); // Hi, my name is Jane!










