首先,我想说我真的尝试过搜索这个问题,因为我觉得以前好像有人问过这个问题。也许我使用了错误的术语,但我还没有找到任何东西。无论如何,问题是:
假设我有一个父类:
function Parent(){
this.say = function(words){
console.log(words);
};
}
还有一个继承于此的子类:
function Child(){
Parent.call(this);
}
我希望子类具有 say
函数,但我想预定义参数。例如,执行此操作的非理想方法是通过添加以下内容来重写函数:
this.say = function(){
console.log("hello")
}
但我更愿意以某种方式调用父级的 say 函数并指定参数“hello”
你会怎么做?或者 - 这是考虑 javascript 继承的错误方法吗?如果是,您会推荐什么?
最佳答案
正确的做法是将所有实例共享的方法放在原型(prototype)上,并将实例特定的代码放在构造函数中。
如果您愿意,您可以重写子级原型(prototype)上的任何方法:
function Parent(){ }
Parent.prototype.say = function(words) {
console.log(words);
};
function Child() {
Parent.call(this); // apply parent constructor to instance
}
Child.prototype = Object.create(Parent.prototype); // establish inheritance
Child.prototype.constructor = Child;
Child.prototype.say = function() { // override method
// call parent method with specific argument
Parent.prototype.say.call(this, 'hello');
};
.call
(和 .apply
)让您调用函数并显式设置 this
在函数内应引用的内容。在本例中,我们调用父构造函数的 .say
方法,但由于我们还传递了 this
,所以就像在 实例上调用该方法一样> child
。
关于javascript - 在 javascript 中增强继承的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20572830/