【问题标题】:How to call Parent Method from the Overriding Method in Child class如何从子类中的覆盖方法调用父方法
【发布时间】:2014-05-11 11:30:04
【问题描述】:

如何从父类访问在子类中被覆盖的方法? 在下面的示例中,我想在覆盖中调用 bar.my_name() 方法 foo.my_name() 中的方法

function bar() {
  this.my_name = function() {
    alert("I Am Bar");
  }
}

function foo() {
  this.my_name = function() {
    alert("I Am Foo");
    //access parent.my_name()
  }
}

foo.prototype = Object.create(bar.prototype);
foo.prototype.constructor = foo;

var test = new foo();
test.my_name();

【问题讨论】:

  • 您在示例代码中根本没有使用原型。设置 foo.prototype 没有任何作用,因为 bar 只有实例变量。也许下面的答案可以帮助你理解 JavaScript 原型:stackoverflow.com/a/16063711/1641941

标签: javascript class inheritance methods overriding


【解决方案1】:

你可以这样做:

(new bar()).my_name.call(this);

我认为您对原型的工作方式有些困惑,因为它们在这里并没有真正帮助您。

这可能会稍微好一点:

var bar = {
    my_name: function () {
        console.log('bar name');
    }
};

var foo = Object.create(bar);

foo.my_name = function () {
    console.log('foo name');
    bar.my_name.call(this);
};

或者如果你想使用构造函数,像这样:

function Bar () {}

Bar.prototype.my_name = function () {
    console.log('bar name');
};

var foo = Object.create(Bar.prototype);

foo.my_name = function () {
    console.log('foo name');
    bar.my_name.call(this);
};

但我不太确定您要做什么或为什么,所以如果有更多的上下文,给您更好的建议会更容易。

【讨论】:

  • 我认为这适合我想要完成的工作。可能我只是需要对原型有更好的理解。
【解决方案2】:

一种可能的解决方案是将方法移至基类原型。

function bar() {
}

bar.prototype.my_name = function() {
  alert("I am bar");
}

function foo() {
}

foo.prototype = Object.create(bar.prototype);
foo.prototype.my_name = function() {
    alert("I Am Foo");
    bar.prototype.my_name.call(this);
}

foo.prototype.constructor = foo;

var test = new foo();
test.my_name();

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 2020-11-04
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多