javascript inheritance
NickName:xandy Ask DateTime:2009-05-31T16:44:58

javascript inheritance

I know there is a lot of similar questions are tons of great answers to this. I tried to look at the classical inheritance methods, or those closure methods etc. Somehow I consider they are more or less "hack" methods to me, as it doesn't really what the javascript is designed to do. (Welcome anybody correct me if I am wrong). OK, as long as it works, I satisfy with the classical inheritance pattern like:

PARENTClass = function (basevar) { do something here; };
PARENTClass.prototype = { a: b, c: d}; // prototype is auto gen 

// Inheritance goes here
CHILDClass = function (childvar) { do something; };
CHILDClass.prototype = new PARENTClass(*1); // Actual inheritance to the prototype statement
// Instance
CHILDInstance = new CHILDClass(whatever);

Above is somehow, to my understanding the inheritance of JS. But one scenario I have no idea how to implement, is that what if I want to do some initializing DURING object creation (ie, within constructor), and the new object can be used right away.... My illustration on problem might not be too clear, so let me use the following C# Psuedo to explain what I want to do:

class PARENT {
    public PARENT (basevar) { ... }
}
class CHILD : PARENT {
    public CHILD (basevar) : PARENT (basevar) // constructor of child, and call parent constructor during construct.
    { ... }
}

For some reason (like init. UI elements), putting them in constructor seems the best way to do. Anyone have idea on how can I do it.

PS: in the *1, I have no idea what I should put there. PS2: The above situation I DID found the jquery.inherit library can do, I just wonder if not using library can achieve it. PS3: Or my understanding is wrong. Since javascript is not intended to mimick OOP (that's why i call it hack), what is the "CORRECT" logic to implement this.

Copyright Notice:Content Author:「xandy」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/931660/javascript-inheritance

Answers
Alex Rozanski 2009-05-31T09:24:29

It is not a hack as such; JavaScript is a prototyped language, as defined by Wikipedia as where:\n\n\n ..classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes.\n\n\nAs it says, classes are not used in JavaScript; each object that you create is descended from the JavaScript Object; all objects in JavaScript have the prototype object, and all instances of objects you create 'inherit' methods and properties from their object's prototype object. Take a look at the MDC prototype object reference for more information.\n\nAs of this, when you call the line:\n\nCHILDClass.prototype = new PARENTClass();\n\n\nThis allows the CHILDClass object to add methods and properties to its prototype object from the PARENTClass object, which creates an effect similar to the idea of inheritance present in class-based languages. Since the prototype object affects every instance created of that object, this allows the parent object's methods and properties to be present in every instance of your child object.\n\nIf you want to call your parent class's constructor in your child class's constructor, you use the JavaScript call function; this allows you to call the parent class's constructor in the context of the child class's constructor, therefore setting the newly prototyped properties in your child class to what they are set as in the parent class.\n\nYou also do not need to put anything where you have specified the *1, since that line is merely used to add the methods and properties to the child class's prototype object; however, bear in mind that it calls the parent class's constructor, so if there are any arguments that are fundamental in the operation of the parent class constructor, you should check that these are present so as to avoid JavaScript errors.",


Ayman Hourieh 2009-05-31T09:01:27

You can manually invoke the parent constructor in the subclass constructor like this:\n\nCHILDClass = function (basevar) {\n PARENTClass.call(this, basevar);\n // do something;\n};\n\n\nThe trick here is using the call method, which allows you to invoke a method in the context of a different object. See the documentation of call for more details.",


Christoph 2009-05-31T11:27:16

JavaScript has no built-in support for inheritance hierarchies as type extension is supposed to be done via aggregation, ie adding desired functionality directly to the object itself or its prototype if the property is to be shared between instances.\n\nNevertheless, JS is powerful enough to make implementing other forms of object construction possible, including classical inheritance.\n\nGiven a clone function - which is enough to add 'true' prototypical inheritance, and not JavaScript's bastardization thereof - your exampe can be implemented like this:\n\nfunction ParentClass(baseVar) {\n // do stuff\n}\n\n// don't overwrite the prototype object if you want to keep `constructor`\n// see http://joost.zeekat.nl/constructors-considered-mildly-confusing.html\nParentClass.prototype.a = 'b';\nParentClass.prototype.c = 'd';\n\nfunction ChildClass(childVar) {\n // call the super constructor\n ParentClass.call(this, childVar);\n}\n\n// don't inherit from a ParentClass instance, but the actual prototype\nChildClass.prototype = clone(ParentClass.prototype);\nChildClass.prototype.e = 'f';\n\n\nIt's also possible to add some syntactic sugar for class-based inheritance - my own implementation can be found here.\n\nThe example from above would then read\n\nvar ParentClass = Class.extend({\n constructor: function(baseVar) {\n // do stuff\n },\n a: 'b',\n c: 'd'\n});\n\nvar ChildClass = ParentClass.extend({\n e: 'f'\n});\n",


mythz 2009-07-30T19:27:09

I've got a lightweight javascript OOP wrapper that provides 'Class-like' inheritance where you can override base methods or call base constructors or members.\n\nYou define your classes like this:\n\n//Define the 'Cat' class\nfunction Cat(catType, firstName, lastName)\n{\n //Call the 'Animal' constructor.\n Cat.$baseNew.call(this, firstName, lastName);\n\n this.catType = catType;\n}\n//Extend Animal, and Register the 'Cat' type.\nCat.extend(Animal, { type: 'Cat' }, {\n hello: function(text)\n {\n return \"meaoow: \" + text;\n },\n getFullName: function()\n {\n //Call the base 'Animal' getFullName method.\n return this.catType + \": \" + Cat.$base.getFullName.call(this);\n }\n})\n\n//It has a built-in type system that lets you do stuff like:\n\nvar cat = new Cat(\"ginger\", \"kitty\", \"kat\");\nCat.getType() // \"Cat\"\ncat.getBaseTypesAndSelf() // [\"Cat\",\"Animal\",\"Class\"]\ncat.getType() // \"Cat\"\ncat.isTypeOf(Animal.getType()) // \"True\"\n\nvar dynamicCat = Class.createNew(\"Cat\", [\"tab\",\"fat\",\"cat\"])\ndynamicCat.getBaseTypesAndSelf() // [\"Cat\",\"Animal\",\"Class\"]\ndynamicCat.getFullName() // tab: fat cat\n\n\nsource code available at: Class.js\n\nI also have more details in my blog post about OOP in javascript",


More about “javascript inheritance” related questions

Class Inheritance in Javascript

I am wondering how to simulate Class Inheritance in JavaScript. I know class doesn't apply to JavaScript, the way we use is Functions to create objects and do the inheritance things through Prototype

Show Detail

Javascript inheritance

I'm trying a few different approaches to Javascript inheritance at the moment. I have the following code: ('borrowed' from http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm) KV...

Show Detail

JavaScript inheritance

Douglas Crockford seems to like the following inheritance approach: if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; ...

Show Detail

Javascript Privilege Function Inheritance

I have spent the past few weeks doing a ton of research on Javascript inheritance. Firstly, I want to say that I am NOT trying to implement class-based inheritance in Javascript, however, I am tryi...

Show Detail

What is differential inheritance in JavaScript?

This answer on Object.create() method in JavaScript in SO talks about differential inheritance. It goes on to say this : This methods allows you to easily implement differential inheritance, w...

Show Detail

Implement multiple inheritance in Javascript

I have observed that through the use of "prototype" property in Javascript (and indirectly setting up the prototype chain), one can implement multi-level inheritance in JavaScript. But is it possib...

Show Detail

javascript inheritance

I know there is a lot of similar questions are tons of great answers to this. I tried to look at the classical inheritance methods, or those closure methods etc. Somehow I consider they are more or...

Show Detail

Javascript inheritance misbehaviour

I have some js code here link deleted If you open your js console and you'll run this code snipet var r = new TempPopupForm("xxx"); r.create(); an error will appear TypeError: this.init is not a

Show Detail

Javascript inheritance implementation question

In his sitepoint article about javascript inheritance, Harry Fuecks explains a way of implementing inheritance as follows: function copyPrototype(descendant, parent) { var sConstructor = p...

Show Detail

Using inheritance patterns in JavaScript

From my experiance, JavaScript does this: manipulating the DOM or other host objects adding event handlers doing Ajax Since I started digging into prototypal inheritance, I would like to know how...

Show Detail