Rana Deep
Rana Deep

Reputation: 617

Setting __proto__ of prototype of a Constructor

I am inheriting from a Base class to Derived class like this :

say Base is View and Derived is ItemVIew

function ItemView(){
View.call(this);
}

ItemView.prototype.__proto__ = View.prototype 

Can the above be acheived with just

Iteview.prototype = new View;

Also i have another question

When i set ItemView.prototype.__proto__ = View.prototype ,The prototype of ItemView is Function.prototype and that means i am setting Function.prototype.__proto__ = View.prototype so all the methods of View.prototype are inherited by every other Constructor i define ?

Can i solve it by just ItemView.__proto__ = View.prototype ?

Which is the reccomended way of Extending a Base class like View so that ItemView is still a constructor ?

Upvotes: 1

Views: 85

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

The object referenced by ItemView.prototype is what will be assigned as the underlying prototype of objects created via new ItemView. ItemView.prototype.__proto__ is likely (on implementations that have it) to be Object.prototype.

But no, you don't want to do ItemView.prototype = new View(); -- what if View needs arguments? This is a very common error.

Instead, in a pre-ES5 environment:

function Temp() {
}
Temp.prototype = View.prototype;
ItemView.prototype = new Temp();
ItemView.prototype.constructor = ItemView;

In an ES5 environment:

ItemView.prototype = Object.create(View.prototype);
ItemView.prototype.constructor = ItemView;

...and continue to do your View.call(this) from within ItemView.

Upvotes: 4

Related Questions