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?
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?
Share Improve this question edited Mar 12, 2011 at 22:25 Robert Harvey 181k48 gold badges348 silver badges512 bronze badges asked Mar 12, 2011 at 22:22 Richard HollandRichard Holland 2,6832 gold badges23 silver badges35 bronze badges3 Answers
Reset to default 13In 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.
The book also says "this is bound to the wrong value". Is the "wrong" value of "this" the global object? The way Crockford fixes it makes me uncertain. Couldn't he have fixed it in a way more familiar to people with a "classic" background just by calling this.helper(), ie making helper() a public method? I would guess yes and guess that he did it the way he did it just to (also) show a workaround that still uses a function invokation pattern, but would like to have that confirmed; being new to javascript am not sure my guesses are correct.