Can Javascript classes/objects have constructors and how are they created? Any examples?
If I would get this comment, I'd delete my answer right away
Philippe Leybaert
2009-07-11 16:32:27
Because you're lazy. The links posted contain plenty of examples. The person answering your question made an effort to look up these links for you, and you still want more. I find it rather rude to suggest you're only going to accept his answer if he he gives you everything on a plate. Just MHO.
Philippe Leybaert
2009-07-11 16:55:30
+2
A:
If you have an hour or so this is an excellent lecture the covers this topic.
Douglas Crockford: "Advanced JavaScript"
x13
2009-07-11 16:39:09
+1
A:
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 new MyClass()
will return is an object with only the properties assigned to the this
object and in the prototype
object of the "class."
var MyClass = (function () {
// private static
var nextId = 1;
// constructor
var cls = function () {
// private
var id = nextId++;
var name = 'Unknown';
// public (this instance only)
this.get_id = function () { return id; };
this.get_name = function () { return name; };
this.set_name = function (value) {
if (typeof value != 'string')
throw 'Name must be a string';
if (value.length < 2 || value.length > 20)
throw 'Name must be 2-20 characters long.';
name = value;
};
};
// public static
cls.get_nextId = function () {
return nextId;
};
// public (shared across instances)
cls.prototype = {
announce: function () {
alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
}
};
return cls;
})();
Blixt
2009-07-11 16:53:12
Just a note about the `cls.prototype` part: "shared across instances" is only for reading the value (calling `announce`). If you set `myClassInstance.announce` to another value, it creates a new property in `myClassInstance`, so it only applies to that object, not other instances of the class. Assigning to `MyClass.prototype.announce` will affect all instances though.
Matthew Crumley
2009-07-11 18:55:38
+1
A:
Click Upvote, your code sample is wrong. You're alerting an object, not the colour. Also the getColor function is defined locally to the constructor, not to the class.
function Box(color)
{
this.color=color;
this.getColor = function()
{
return this.color;
}
}
var blueBox=new Box("blue");
alert(blueBox.getColor()); //wlll print blue
var greenBox=new Box("green");
alert(greenBox.getColor()); //wlll print green
Nick
2009-07-12 08:29:31