简体   繁体   中英

Extend prototype function JavaScript

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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