The difference between the method determined using the following two

Snippet1:

var box = function() {}; box.prototype.open = function { }; 

Snippet2:

  var box = function() { this.open = function() { }; } 

Any difference between the two, which one is better?

+4
source share
2 answers

Suppose box is a constructor, so are you doing new box() ?

If so...

  • The first version will share the open function among all objects created from the box constructor.

  • The second generates a new function object for each object created by the box constructor.

Thus, the former will be more memory efficient than the latter.


First version:

  new box box prototype object prototype +--------------+ +--------------+ +--------------+ | | | | | | | |--------->| open func |--------->| | | | / | | | | +______________+ / +______________+ +______________+ / / new box / +--------------+ / | | / | |/ | | +______________+ 

Second version:

  new box box prototype object prototype +--------------+ +--------------+ +--------------+ | | | | | | | open func |--------->| |--------->| | | | / | | | | +______________+ / +______________+ +______________+ / / new box / +--------------+ / | | / | open func |/ | | +______________+ 
+5
source

@am, I'm wrong. The first way is an effective way to do this. The second method is useful if you need private variables.

 var box = function() { var _message = "hello world"; this.func2 = function(){ console.log(_message); // prints hello world } }; box.prototype.func1 = function() { this.func2(); // prints hello world console.log(_message); // throws ReferenceError: _message is not defined }; 
+5
source

Source: https://habr.com/ru/post/1391071/


All Articles