Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从子方法中调用父方法?_Javascript_Oop_Prototypal Inheritance - Fatal编程技术网

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;
}

但我的情况并非如此。My
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

作为旁注,使用
B.prototype=new a()
将执行
A
的构造函数,这可能不是您想要的,并且可能会导致不必要的副作用。您可以使用
B.prototype=Object.Create(A.prototype)
以获得相同的结果,但不会执行
A
的构造函数。当然,您需要确保
hello
是实际
A.prototype
的一部分,请参阅