Can Javascript classes/objects have constructors and how are they created? Any examples?
|
Original answer:
Alternative where color resembles a private member variable:
Usage:
|
|||||||||||||||||
|
Here's a template I sometimes use for OOP-similar behavior in JavaScript. As you can see, you can simulate private (both static and instance) members using closures. What
I've been asked about inheritance using this pattern, so here goes:
And an example to use it all:
As you can see, the classes correctly interact with each other (they share the static id from One thing to note is the need to shadow instance properties. You can actually make the For methods on the prototype you don't need to worry about the above though, if you want to access the super class' prototype methods, you can just call |
|||||||||||||||||
|
It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming). lunched-dan was closer but the example didn't work in jsFiddle. This example creates a private constructor function that only runs during the creation of the object.
If you wanted to assign public properties then the constructor could be defined as such:
|
|||||||||||
|
The point of the constructor property is to provide some way of pretending JavaScript has classes. One of the things you cannot usefully do is change an object's constructor after it's been created. It's complicated. I wrote a fairly comprehensive piece on it a few years ago: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html |
|||
|
Here are a couple of excellent explanations: |
|||
|
I guess I'll post what I do with javascript closure since no one is using closure yet.
Comments and suggestions to this solution are welcome. :) |
|||
|
Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:
|
||||
|
is a constructor. When you do var myObj = new MyClass(); the MyClass is executed and a new object is returned of that class. |
|||
|
This pattern has served me well. With this pattern, you create classes in separate files, load them into your overall app "as needed".
|
|||||||||||
|
I found this tutorial very useful. This approach is used by most of jQuery plug-ins.
Now ,
|
|||
|