Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are helper methods frequently used in Javascript?

Tags:

javascript

New to Javascript, reading Crockford's Javascript: The Good Parts (among other things)

In the 4th chapter regarding functions Crockford is showing how to preserve this in the outer function for use in inner functions, which I understand.

My question is, in his example code and a ton more like it, why use this helper function:

myObject.double = function() {
  var that = this; 

  var helper = function () {
      that.value = add(that.value, that.value);
  }
  helper();
};

Is it maybe because add() is sitting out in global scope, while value is in myObject, so I need to copy this (myObject) then transfer to global where I can grab add()?

Otherwise I'm not sure why I need the helper function?

like image 410
Richard Holland Avatar asked Mar 12 '11 22:03

Richard Holland


2 Answers

In that section of the book he is demonstrating that it is conventional to use that when accessing the this object of a function's parent.

It is not necessary to use a helper function do do what the code does. It is just an example to illustrate how to get around scoping issues with the this object.

like image 63
Peter Olson Avatar answered Sep 21 '22 15:09

Peter Olson


Encapsulation. The helper() in your example only exist in the scope of myObject.double() it won't be available / visible outside of it. I believe that it is called private method instead of "helper" function.

like image 43
airmanx86 Avatar answered Sep 20 '22 15:09

airmanx86