The memory footprint of the first one will always be larger. Consider prototype
as a shared package of methods that all instances can use. It is effective because you don't create a new function for every instance, but you're reusing the existing method already in memory.
The good news is that the two ways you showed can be combined.
MyClass = function () {
var x;
// public method with access
// to private variables
this.sayX = function () {
alert(x);
};
}
// method that doesn't need access to private variables
MyClass.prototype.sharedMethod = function () {
// ...
}
But as far as you're dealing with small codebase, you shouldn't worry about memory usage. You can even use patterns like
// everything will be created for every
// instance, but the whole thing is nicely
// wrapped into one 'factory' function
myClass = function () {
// private variables
var x;
// private methods
function doSomethingWithX() {}
// public interface
return {
sayX: function () {
alert(x);
},
publicMethod: function () { .. },
// ...
};
};
Note, I intentionally changed myClass to lowercase, because it's no longer a constructor function and there's no need to use new
when invoking!
UPDATE - there's a third pattern which well suits your needs:
MyClass = function (x, y, whatever) {
this._init.apply(this, arguments);
}
// The prototype creates a scope for data hiding.
// It also includes a constructor function.
MyClass.prototype = (function () {
var x; // private
return {
_init: function (x_in) {
x = x_in;
},
sayX: function () {
alert(x);
},
// ...
};
})();