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 acplish this in native JavaScript without the aid of libraries?
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 acplish this in native JavaScript without the aid of libraries?
Share Improve this question asked Jul 18, 2015 at 18:40 Jack GuyJack Guy 8,5238 gold badges60 silver badges88 bronze badges 02 Answers
Reset to default 4if 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();
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.