- 在类定义内部直接添加方法
class Animal {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
}
- 使用
Object.defineProperty
class Animal {
constructor(name) {
this.name = name;
}
}
Object.defineProperty(Animal.prototype, 'sayHello', {
value: function() {
console.log(`Hello, I'm ${this.name}`);
},
enumerable: false,
writable: true,
configurable: true
});
- 直接在原型对象上添加方法
class Animal {
constructor(name) {
this.name = name;
}
}
Animal.prototype.sayHello = function() {
console.log(`Hello, I'm ${this.name}`);
};