Extend JavaScript Function Prototype

I have an object that inherits from another object, for example:

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 method b, which is also called "foo", and extends a function with the same name.

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

Is there an easy way to do this in native JavaScript without the help of libraries?

+4
source share
2 answers

If you understand 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();
Run codeHide result
+3
source

The easiest option:

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

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

The best option:

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

b.prototype.foo() a.prototype.foo(), . a.prototype.foo(), b.prototype.foo(), .

+1

Source: https://habr.com/ru/post/1598528/


All Articles