When you set print
directly on the object (with this.print
) you use some memory to store the property (here method) for each object (instantiation of your class). When you define it on the prototype, all the instances will share the same property (so the same memory).
You will also have some troubles to use inheritance.
If you only want one instance of your "class", you certainly should use a pattern singleton. But for a more powerful solution I would suggest you to try a framework implementing a dependency injection component because singleton is almost an anti-pattern. You can find an example of this kind of framework following the link in my profile (you cannot use it without a node.js server but it is a nice example).
Finally, you may define your class like the following:
var Class = function() {
this._x = 25; // Public variable
this._y = 10; // Private variable
}
Class.prototype.print = function() {
alert(this._x + this._y);
}
Object.defineProperty(Class.prototype, 'x', {
get: function() { return this._x; }
});
var obj = new Class();
obj.print();
alert(obj.x);
alert(obj.y);