我有这样一段代码:
function A() {
this.hello = function() {
console.log("I'm A");
}
}
function B() {
this.hello = function() {
// I need to call A.hello here, like parent.hello();
B.prototype.hello(); // This is wrong, TypeError
console.log("I'm B");
}
}
B.prototype = new A();
var b = new B();
b.hello();
#=> TypeError: Cannot call method 'hello' of undefined
我在这里读到一些类似的问题,但他们都使用这种技术,他们将方法分配给 prototype
。
FaqPage.prototype.init = function(name, faq) {
BasePage.prototype.init.call(this, name);
this.faq = faq;
}
FaqPage.prototype.getFaq = function() {
return this.faq;
}
但这不是我的情况。我的 prototype
是父级的实例。在我的情况下如何调用父方法?还是我必须重构我的代码?
最佳答案
您需要为 this.hello
分配一个值,此时您只是创建一个要运行的函数。
尝试以下操作:
function A() {
this.hello = function() {
console.log("I'm A");
}
}
function B() {
this.hello = function() {
B.prototype.hello(); // Now runs correctly and logs "I'm A"
console.log("I'm B");
}
}
B.prototype = new A();
var b = new B();
b.hello();
通过将代码更改为 this.hello = function() { }
,我们正在创建可以从对象外部调用的对象属性。
调用b.hello();
的结果是:
I'm A
I'm B
关于javascript - 如何从子方法中调用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214909/