Acceptability of public fields in JavaScript

1.7k Views Asked by At

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?

Example

"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;
};
2

There are 2 best solutions below

3
On BEST ANSWER

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.

2
On

JavaScript is JavaScript, not any other language. People coming from Java have this tendency to assume everything should work like Java. That's wrong. JavaScript is in fact so far away from Java that few of their structural rules are similar. JavaScript is a prototype-oriented, loosely typed functional language, and as such it can mimic Java to an extent, but there is no reason at all why it should. Generally speaking, if you don't find a cros-language, common-sense reason for a certain mantra regarding JavaScript, ignore it.