Created
March 4, 2013 14:09
-
-
Save AugustoPedraza/5082449 to your computer and use it in GitHub Desktop.
var sum = add(3, 4); //sum is 7 When a function is invoked with this pattern, "this" is bound to the global object. If the methods defines a variable and assigns it the value of "this", the inner function will have access to "this" through that variable. By convention, the name of that variable is "that". This text and example was taken from the…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Augment myObject with a double method. | |
add = function(a, b){ return a + b; }; | |
var myObject = { value: 0 }; | |
myObject.double = function( ){ | |
var that = this; //Workaround | |
var helper = function( ){ that.value = add(that.value, that.value); }; | |
helper( ); //Invoke helper as a function | |
}; | |
console.log(myObject.value); //Show 0 | |
myObject.value = 2; | |
myObject.double( ); | |
console.log(myObject.value); //Show 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment