JavaScript中的继承:调用父';s法
下面的示例显示了我在JavaScript中实现继承的方式。我试图从子类调用父类的方法。我在网上看到了许多示例,它们将父方法添加到原型中,并使用call或apply函数(但我的实现没有这样做)。有没有办法打这种电话JavaScript中的继承:调用父';s法,javascript,oop,inheritance,Javascript,Oop,Inheritance,下面的示例显示了我在JavaScript中实现继承的方式。我试图从子类调用父类的方法。我在网上看到了许多示例,它们将父方法添加到原型中,并使用call或apply函数(但我的实现没有这样做)。有没有办法打这种电话 function classM() //parent class { this.myName = function() { console.log('parent'); } } function classEM () { classM.
function classM() //parent class
{
this.myName = function()
{
console.log('parent');
}
}
function classEM ()
{
classM.call(this);
this.myName = function()
{
console.log('child');
//HOW DO I CALL myName() of the parent class?
}
}
classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;
var rm = new classEM();
rm.myName(); //should print child and then parent
当您在
classEM
中执行this.myName=…
时,您将用classEM
中的函数替换父级创建的旧myName
函数。所以现在只有一个函数存在。相反,您可以在classM
的原型中添加myName
函数并从中继承
所以程序变成了这样
function classM() {}
// Add myName to the parent
classM.prototype.myName = function() {
console.log('parent');
}
function classEM() {
this.myName = function() {
// Get the parent prototype object and invoke the myName in it.
Object.getPrototypeOf(this).myName();
console.log('child');
}
}
classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;
var rm = new classEM();
rm.myName();
输出
parent
child
你不能像那样改变构造函数,失败!您没有在
classM
上使用原型继承,因此Object.create(classM.prototype)
返回一个没有myName
方法的对象。当您执行classM.call(this)
时,对象将获得方法,但随后您将覆盖它,因此不,您不能调用它。@adeno您是什么意思?请多点specific@cookiemonster我明白,但是有没有办法解决这个问题?如果你想同时调用myName
方法,为什么不在classEM
内部创建一个classM
的新实例并调用darn方法呢?我提出了同样的解决方案,但不是对象。getPrototypeOf(this).myName();我叫classM.prototype.myName.call(this);。你知道你的方法和这个方法有什么不同吗?@FranXh好吧,我的方法在this
上有灵活性。我们可以动态地更改这个对象:-)我明白了。我问这个问题的原因主要是因为JavaScript中的“this”和“that”用法。我在里面用“那个”functions@FranXh通常,当我们定义内部函数时,如果它们需要保留外部函数的this
,我们将其存储在常规变量that
中,作为var that=this
。除此之外,我们不必太担心那件事