Javascript 如何从子方法中调用父方法?
我有这样一个密码:Javascript 如何从子方法中调用父方法?,javascript,oop,prototypal-inheritance,Javascript,Oop,Prototypal Inheritance,我有这样一个密码: 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,
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
我在这里读到了一些类似的问题,但它们都使用这种技术,它们为原型指定了一种方法
FaqPage.prototype.init = function(name, faq) {
BasePage.prototype.init.call(this, name);
this.faq = faq;
}
FaqPage.prototype.getFaq = function() {
return this.faq;
}
但我的情况并非如此。Myprototype
是一个父实例。在我的情况下,如何调用父方法?还是我必须重构我的代码 您需要为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
作为旁注,使用B.prototype=new a()
将执行A
的构造函数,这可能不是您想要的,并且可能会导致不必要的副作用。您可以使用B.prototype=Object.Create(A.prototype)
以获得相同的结果,但不会执行A
的构造函数。当然,您需要确保hello
是实际A.prototype
的一部分,请参阅