inheritance - Extend prototype function JavaScript - Stack Overflow

I have an object that inherits from another object, like so:var a = function (){}a.prototype.foo = fu

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745180506a4615396.html

相关推荐

  • inheritance - Extend prototype function JavaScript - Stack Overflow

    I have an object that inherits from another object, like so:var a = function (){}a.prototype.foo = fu

    3小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信