6

I have an object that inherits from another object, like so:

var a = function ()
{

}
a.prototype.foo = function ()
{
    bar();
}

var b = function ()
{
    a.call(this)
}
b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

I want to have a method of b that is also named "foo" and extends a's function with the same name.

b.prototype.foo = function ()
{
    baz();
    // When .foo() is called, runs both bar() and baz()
}

Is there a simple way to accomplish this in native JavaScript without the aid of libraries?

0

2 Answers 2

4

if i understand you correctly you can extend the method

function A() {}

A.prototype.foo = function() {
    console.log('foo');
};

function B() {}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.foo = function() {
  A.prototype.foo.call(this);
  console.log('foo2');
}

var b = new B();

b.foo();

Sign up to request clarification or add additional context in comments.

Comments

1

The simplest option:

b.prototype.foo = function () {
    bar();
    baz();
}

But if you make changes to a.prototype.foo, you will need to update b.prototype.foo with the same logic.

The better option is:

b.prototype.foo = function () {
    a.prototype.foo.call(this); 
    baz();
}

Now b.prototype.foo() calls a.prototype.foo() followed by its own internal logic. If you change a.prototype.foo(), those changes will be immediately reflected in the behaviour of b.prototype.foo() without requiring wider refactoring.

1 Comment

That always happens. @Georgii Kats just beat me to it with the second solution, so make sure he gets the official answer if it's what you're looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.