Search code examples
javascriptprototype

Setting prototypes inside function constructor


var a = function(){
    this.sayFoo = function(){
        console.log('foo');
    };
}

var b = function(){
    console.log(this.prototype); //undefined
    this.sayBar = function(){
        console.log('bar');
    };
}

b.prototype = new a();

var bInst = new b();

bInst.sayFoo();
bInst.sayBar();

console.log(b.prototype); //a {sayFoo: function}

http://jsfiddle.net/KbBny/1/

How do I add sayBar to the b prototype inside the function constructor?

Does b.prototype = new a(); overwrite the prototype, or merge b's with a's?


Solution

  • Does b.prototype = new a(); overwrite the prototype, or merge b's with a's?

    It does overwrite it with a new a instance; nothing is merged (for example you'd need to update the b.prototype.constructor property). That's why you do add all properties to b.prototype after this line. However, actually you don't want to create an instance, but just set up the prototype chain correctly:

    b.prototype = Object.create(a.prototype);
    

    How do I add sayBar to the b prototype inside the function constructor?

    You should not add it to the prototype, as it is not a prototype (shared) method - it's instance-specific to every a instance (at least it should be, otherwise you would put it on a.prototype and then it gets covered by above line). To get the instance method on all b instances as well, you use

    var b = function(){
        a.call(this); // invoke the `a` constructor on this instance
    };