Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inheritance: when constructor has arguments

Using pure JavaScript to do inheritance, this is what I usually do:

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

Since there is no arguments to pass into the constructor, new A has nothing to complain about. Now, I haven't figured out a good way to do inheritance if the constructor has arguments to pass. For example,

function A(x, y) {} A.prototype.run = function () {};  function B(x, y) {} B.prototype = new A; B.prototype.constructor = B; 

I could pass some arbitrary values like:

B.prototype = new A(null, null); 

In some cases, I may need to validate x and y in the constructor of A. In some extreme cases, I need throw errors when checking x or y. Then, there is no way for B to inherit from A using new A.

Any suggestions?

Thanks!

like image 268
Grace Shao Avatar asked Sep 23 '11 18:09

Grace Shao


People also ask

Are constructors inherited in JavaScript?

Conclusion. The constructor property is a piece of the inheritance mechanism in JavaScript.

What is difference between __ proto __ and prototype?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.

Does JavaScript support multilevel inheritance?

An object can be inherited from multiple other objects, i.e. the object has common property from other parent objects not only a single parent. In JavaScript, this can be achieved by merging properties from different properties into one single object.

How inheritance is implemented in JavaScript?

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.


1 Answers

Well, if you want to make B.prototype an object that inherits from A.prototype, without executing the A constructor, to avoid all possible side-effects, you could use a dummy constructor to do it, for example:

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

You could create a function to encapsulate the logic of the creation of this new object, e.g.:

function inherit(o) {   function F() {}; // Dummy constructor   F.prototype = o;    return new F();  }  //... B.prototype = inherit(A.prototype); B.prototype.constructor = B; 

If you target modern browsers, you could use the ECMAScript 5 Object.create method for the same purpose, e.g.:

B.prototype = Object.create(A.prototype); B.prototype.constructor = B; //.. 
like image 143
Christian C. Salvadó Avatar answered Sep 18 '22 13:09

Christian C. Salvadó