yossi
yossi

Reputation: 1431

Why can't I call a prototyped method in Javascript?

jsFiddle Demo

I have F which inherits from Shape.

F.prototype = Shape.prototype;

F creates new method with name test.

F.prototype.test = function(){return 'test';};

I understand that if I write F.prototype = Shape.prototype; all the methods which I create in F will be available by other class which inheritance from Shape.

What have I done wrong?

Why do I get errors when I execute the code alert(B.test());?

function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};

var F = function(){};
F.prototype = Shape.prototype;
F.prototype.test = function(){return 'test';};


function Triangle(side, height) {
this.side = side;
this.height = height;
}

Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';

var my = new Triangle(5, 10);
alert(my.toString());

var Second_class = function(){};
Second_class.prototype = Shape.prototype;
B.prototype = new Second_class();
alert(B.test());

in this example when F which inherits from Shape and Triangle created from F jsFiddle demo woek well

Upvotes: 1

Views: 367

Answers (1)

Bergi
Bergi

Reputation: 664246

I have F which inheritance from Shape.

F.prototype = Shape.prototype;

Strictly speaking, you're not. You are overwriting the prototype property of the F function. To build a real inheritance chain, you would need to use

F.prototype = Object.create(Shape.prototype);

so that Shape's properties are still available on F instances, but not the other way round (as both prototypes were the same object). So to answer your first question: Yes, you did.

See also Why wouldn't I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance?

why when I execution the code alert(B.test()); it is not working ?

That's simple to explain. B (which you forgot to declare in your example, but let's assume it's a function) is a Function object. You don't have any properties assigned to it. What you have done is setting it's prototype property (using the new keyword also sets up the prototype chain correctly, but accidentally creates an instance - Object.create is preferred). So now, any instances of B will inherit from that prototype object:

var b = new B();
b.test();

Upvotes: 2

Related Questions