最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

inheritance - Extend prototype function JavaScript - Stack Overflow

programmeradmin1浏览0评论

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 0
Add a ment  | 

2 Answers 2

Reset to default 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();

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.

发布评论

评论列表(0)

  1. 暂无评论