Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29107

javascript inheritance using the prototype property

I'm trying to do inheritance in javascript. First of all, looking on the web I found this

function A() {}
function B(){}
B.prototype = new A() ;
B.prototype.constructor = B ;

This works, however when I use the prototype property of B it doesn't work anymore ( http://jsfiddle.net/jeanluca/eQBUx/ )

function A() {}
A.prototype.bar = function(){ return 'A'; }

function B() {}
B.prototype.bar = function(){ return 'B'; }

I realize you could do

function B(){ this.bar = function(){ ... } } ;

But I think this is definitely slower than defining it using the prototype. So how could I do inheritance in the second situation ?

Thnx

Upvotes: -1

Views: 76

Answers (3)

Aadit M Shah
Aadit M Shah

Reputation: 74204

Here's your code:

function A() {}
A.prototype.bar = function(){ return 'A';}

function B() {}
B.prototype.bar = function(){ return 'B'; }
B.prototype = new A() ; // replaces B's "bar" with A's "bar

var b = new B ;
console.log(b.bar());

As you can see the problem is in your 6th line. You're first setting B.prototype.bar to a function in line 5 and then you immediately set B.prototype to new A in line 6 (effectively undoing what you did in line 5). The solution is to put line 6 before line 5:

function A() {}
A.prototype.bar = function(){ return 'A';}

function B() {}
B.prototype = new A() ; // now it will work
B.prototype.bar = function(){ return 'B'; }

var b = new B ;
console.log(b.bar());

See the demo for yourself: http://jsfiddle.net/eQBUx/1/

In addition I agree with Bergi: Stop using the new keyword.


Update: After reading your comment and understanding your problem in greater detail I would recommend you use my augment library for inheritance:

var A = Object.augment(function () {
    this.constructor = function () {};

    this.bar = function () {
        return "A";
    };
});

var B = A.augment(function (base) {
    this.constructor = function () {};

    this.bar = function () {
        return "B" + base.bar.call(this);
    };
});

var b = new B;

console.log(b.bar());

See the demo: http://jsfiddle.net/eQBUx/2/

Upvotes: 2

Bergi
Bergi

Reputation: 664207

You're creating a property on a the prototype object which you completely replace afterwards. Do it the other way round, create the bar method on the new object. And don't use new!

function B() {}
// first create the prototype object
B.prototype = Object.create(A.prototype);
// then assign properties on it
B.prototype.bar = function(){ return 'B'; }

Upvotes: 2

Halcyon
Halcyon

Reputation: 57709

Using this to assign properties breaks the prototype chain. It's very inefficient and you can't use it to get inheritance. So .. don't?

Upvotes: 2

Related Questions