1

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

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();
Filburt
  • 17,626
  • 12
  • 64
  • 115
helloworld2013
  • 3,094
  • 5
  • 19
  • 26
  • 1
    You're not using prototype at all in the sample code. Setting foo.prototype doesn't do anything because bar has only instance variables. Maybe the following answer can help you out understanding JavaScript prototype: http://stackoverflow.com/a/16063711/1641941 – HMR Apr 01 '14 at 01:37

2 Answers2

1

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();
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

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.

Tom
  • 1,043
  • 8
  • 16
  • I Think this is appropriate to what I want to accomplish. Probably I just have to have a better understanding with prototypes. – helloworld2013 Apr 01 '14 at 18:50