In Google developers article about JavaScript code optimization, they recommend in the section "Defining class methods" to use prototype to add methods as properties to a function (which is considered as an object in JavaScript).
for instance, instead of defining the methods inside the function constructor body this way:
baz.Bar = function() {
// constructor body
this.foo = function() {
// method body
};
}
methods should be defined using prototype this way:
baz.Bar = function() {
// constructor body
};
baz.Bar.prototype.foo = function() {
// method body
};
But, I have seen a different approach of adding class methods and creating reusable JavaScript code that is used in frameworks like d3.js to implement the core methods which is based on JS closures, for instance:
var nameSpace = {};
nameSpace.myModule = function(module){
var myVar = '';
function exports(){
}
//getter and setter for myVar
exports.myVar = function(_x){
if(!arguments) return myVar;
myVar = _x;
return this; // to allow for method chaining
}
exports.method1 = function(){
//do something
}
exports.method2 = function(){
//do something
}
return exports;
}
and then to use the module:
var test = nameSpace.myModule();
test.method1();
Would this last approach be the answer to the performance and reuse of JavaScript code, otherwise why it is extensively used in framework implementation?
Thanks & regards Mohamed Ali