I'm just wondering if public fields (i.e. those not scoped inside the constructor's closure) are acceptable in JavaScript. While the usual mantra is "don't use public fields, use accessors or properties", I noticed that properties are not yet supported widely across all browsers (IE).
Other languages similar in vein to JavaScript's "everything is public" like Python don't seem to care too much about information hiding and public fields, even those not decorated with properties. So, is it okay to do this in JavaScript?
"Private":
var Class = function()
{
var field = null;
this.getField = function() { return field; };
this.setField = function(value) { field = value; };
};
Public:
var Class = function()
{
this.field = null;
};
We don't care about hiding public information since the source is open and interpreted on the fly by the client.
Properties are not used (they are also slow) commonly and getter functions are also uncommon. There is no private
keyword in Javascript, so wrapping each publicly-accessible prop in a getter/setter method pair would be overkill.
Just write out properties to your objects.
It is a common practice, maybe even a convention, to prefix internal properties with a _
to indicate that they are not intended to be changed or examined by callers.
For example :
function Foo() {
this._meta = {}; // internal use only
this.prop2 = {}; // public use ok
}
Foo.prototype.meta = function(key, val) {
if (val !== undefined) {
this._meta[key] = val;
} else {
return this._meta[key];
}
};
This code shows a public method meta
and an internal property _meta
. The property can be accessed, but developers should realize that if they modify it they can corrupt state.