Javascript object - private methods: which way is better

(function () { function User() { //some properties } //private fn 1 User.prototype._aPrivateFn = function () { //private function defined just like a public function, //for convetion underscore character is added } //private function type 2 //a closure function _anotherPrivateFunction() { // do something } //public function User.prototype.APublicFunction = function () { //call private fn1 this._aPrivateFn(); //call private fn2 _anotherPrivateFunction(); } window.UserX = User; })(); 

// which of the two ways to define private methods of a javascript object is better, especially in terms of memory management and performance.

+4
source share
3 answers

Your "Private Feature # 1" is not private. While version number 2 is closed and, therefore, really only available through your User object.

Often there is no โ€œbestโ€, but in this case, a closed function is completely hidden from the outside world (which is obviously better).

There are still rumors that circuits create memory leaks, which is simply wrong. Closing does not create a memory leak, but the programmer does / can. Your example here is completely perfect.

To have private methods, you have to use an almost exact template.

 var myObject = function() { // privates var a = 5, b = 10, c = a, public = {}; public.getA = function() { return a; }; public.setA = function(v) { a = v; }; function privateOne() { } return public; }; 
+10
source

Creating closures is best if you absolutely must (or want to) hide functions from the outside world.

Adding methods to the prototype is better if you're interested:

  • Memory , because then all instances will have a (single) function, and not create one each.
  • Testability , because you can not test the hidden function inside the cover.
+4
source

JQuery's John Resig has a great presentation on how to create scoops / prototypes / inheritance etc.

http://ejohn.org/apps/learn/

+1
source

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


All Articles