Here is a working example from "Javascript - The Good Parts".
function add(x, y){ return x + y};
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.increment(2);
document.writeln(myObject.value);
myObject.double = function ( ) {
var that = this; // Workaround.
var helper = function ( ) {
that.value = add(that.value, that.value)
};
helper( ); // Invoke helper as a function.
};
myObject.double( );
document.writeln(myObject.value); // 4
For function invocation pattern, 'this' object will have global reference. But I cannot fully understand under-the-hood of mentioned workaround:-
var that = this; // Workaround.
if we do this, aren't we just copying the reference to 'this' to 'that' ? i.e 'that' will hold to global scope same as 'this' ? how does this work internally ?
It's not the same here, this refers to myObject so you're getting the right value property it has, this would refer to window...which is why you want to keep the reference like it's doing.
You can test it out here, a few alerts inside the helper function show what's happening pretty well.
An alternative would be to .call() or .apply() the function with the right context, so this continues to refer to the myObject instance you want...like this:
myObject.double = function () {
var helper = function () {
this.value = add(this.value, this.value)
};
helper.call(this); // Invoke helper as a function.
};
You can test that version here.
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