Created
July 31, 2012 00:30
-
-
Save taybenlor/3212275 to your computer and use it in GitHub Desktop.
Explaining this within JS
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
/* | |
* In JavaScript "this" is very finicky. Mostly it tends to get lost whenever | |
* you use a callback. When you assign a function you're literally creating | |
* a function object and then putting it into an object. Whenever the function | |
* is called it works out what it's this is based on how it was called. | |
* | |
* There are several ways to make sure your this stays around. | |
* | |
*/ | |
function Animal(){ | |
this.hello = "hello"; | |
$('#button').on('click', function(){ | |
console.log(this.hello); | |
// Within this scope the "this" will be lost | |
// because the function is called by JQuery. | |
}); | |
} | |
/* The way that many people solve this problem is by making | |
* a local variable, which will resolve within the function's | |
* closure. | |
*/ | |
function Animal(){ | |
this.hello = "hello"; | |
var self = this; // save this into a local variable | |
$('#button').on('click', function(){ | |
console.log(self.hello); | |
// Notice we use self instead of this here. | |
}); | |
} | |
/* JQuery also provides a method called "proxy" which binds | |
* the this within the funciton (internally it uses the above | |
* method, but externally it looks nicer). | |
*/ | |
function Animal(){ | |
this.hello = "hello"; | |
this.talk = function(){ | |
console.log(this.hello); | |
}; | |
this.talkEvent = $.proxy(this.talk, this); | |
$('#button').on('click', this.talkEvent); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment