简体   繁体   English

如何从子类的重写方法中调用父方法

[英]How to call Parent Method from the Overriding Method in Child class

How can I access a method from a parent class that was overridden in the child class? 如何从子类中被重写的父类访问方法? In My example below I want to call the bar.my_name() method inside the overriding method in foo.my_name() 在下面的示例中,我想在foo.my_name()的重写方法内调用bar.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();

One of possible solutions is to move the method to the base class prototype. 一种可能的解决方案是将方法移至基类原型。

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();

You could do this: 您可以这样做:

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

I think you're a little confused about how prototypes work though, as they're not really helping you here. 我认为您对原型的工作方式有些困惑,因为它们并没有真正帮助您。

This might be slightly better: 这可能会稍微好一点:

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

Or if you want to use constructors, something like 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);
};

But I'm not really sure what you're trying to do or why, so with more context it will be easier to give you better advice. 但是我不确定自己要做什么或为什么做,所以有了更多背景信息,可以为您提供更好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM