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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With