我正在尝试在JavaScript中模拟“类”语法。重新定义对象时,如何从对象的原型中调用该函数?在示例中,我尝试扩展Bear对象的声音功能。
function Animal(name) {
this.name = name;
}
Animal.prototype.sound = function() { console.log("I'm " + this.name); }
function Bear(name) {
Animal.call(this, name)
}
Bear.prototype = new Animal();
Bear.prototype.sound = function() { this.prototype.sound(); console.log("growl!"); }
const cal = new Bear("Callisto")
cal.sound() // Should be: I'm Callisto growl!
console.log(cal)
答案 0 :(得分:1)
您可以直接在Animals原型上访问该方法:
Bear.prototype.sound = function() {
Animal.prototype.sound.call(this);
console.log("growl!");
};