Вопрос

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

Это было полезно?

Решение

As a user, modules impose a performance hit when they contain lots of methods and classes that you don't use. If you just need a few members, you are better off creating them individually as classes instead of importing a full module.

As a browser, there is small computational overhead in initializing a module and namespace, and memory overhead in tracking, but likely not significantly different than the equivalent set of classes and class methods outside of a module.

As a writer, organizing your code into modules when you think the user will typically need all the members is good practice. Better to have a few modules with several related components (a "package") than 25 raw components or one module with all of them. This ease of use and understanding, the compartmentalization into a namespace (which lets you use meaningful names without conflicts to other namespaces), and the grouping of related classes and functions into various modules is why it is typically used in a framework, where you are likely to use most of the components for each module.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top