Private members in JavaScript
Dear UI5-Team,
I have a question with regards to the development guidelines https://github.com/SAP/openui5/blob/master/docs/guidelines.md#creating-classes and to the OpenUI5 source text itself.
The development guideline says
this._bFinalized Private members should have a name starting with an underscore
And in the OpenUI5 source text you can indeed find a lot of public members whose name starts with an underscore,
for example _createTargets in
https://github.com/SAP/openui5/blob/master/src/sap.m/src/sap/m/routing/Router.js
However in JavaScript there are private members, namely the inner functions of the constructor. So I would like to know the reason for marking a member as private with an underscore although it is public. Why not using inner functions?
The main reason was our preference for prototype methods. When we started, closures came at a significant price. And when you start using local constructor functions for private helpers, you end up defining also public methods in the constructor to be able to use the private functions in their implementation.
Well, but you say "public" methods start with an underscore. I guess you mean, functions that are visible as properties on the object?
For UI5, documentation defines what is public and what isn't. That's a quite important rule when consuming UI5 APIs
Thank you! Yes, I mean functions that are visible as properties on the object. One additional question: what do you mean by "closures came at a significant price"? Do you mean all this bind/call stuff?
Using local functions inside the constructor usually isn't all that you need. Often, the private functions also need private state. That you would typically keep in local variables inside the constructor. And when the functions refer to that state, the browser will maintain a closure (essentially another, hidden object) for it. Browser highly optimise this nowadays, but this wasn't the case in all browsers back in 2009.
Another issue is that moving public functions into the constructor (as explained above - to be able to access private functions), also adds a function object for each function for each instance.
E.g. check the following example for illustration:
function MyClass(x) {
this.test = function() { return x;}; // no private members exposes by test
this._x = x; // needed for alternative implementation 'shared'
}
MyClass.prototype.shared = function() {
return this._x;
};
var x = new MyClass(5);
var y = new MyClass(6);
console.log("test is same", x.test === y.test); // false, two different function objects, one for each instance
console.log("shared is same", x.shared === y.shared); // true, same function object shared between instances
If you have many functions and many instances, this can become a disadvantage compared to the prototype approach.
Thank you very much for this detailed explanation!