Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  127] [ 2]  / answers: 1 / hits: 15815  / 13 Years ago, fri, september 23, 2011, 12:00:00

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!


More From » inheritance

 Answers
10

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;
//..

[#89953] Thursday, September 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clifford

Total Points: 86
Total Questions: 114
Total Answers: 111

Location: Wales
Member since Mon, May 17, 2021
3 Years ago
;