Created
July 9, 2012 21:23
-
-
Save apike/3079042 to your computer and use it in GitHub Desktop.
HTML5 CodeCamp Vancouver: "this" in JavaScript
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
// HTML5 CodeCamp Vancouver: "this" in JavaScript | |
var myself = { | |
name: "Allen Pike", | |
company: "Steam Clock Software", | |
affiliations: ["VanJS", "SFU"] | |
}; | |
// "this" C++, Java, etc. | |
// "self" Python, Obj-C | |
html5 == javascript; | |
var zerg = { | |
name: "zergling", | |
health: 35, | |
reportStatus: function() { | |
console.log("Name: " + this.name + | |
" - Health: " + this.health); | |
} | |
}; | |
// Expected case | |
zerg.reportStatus(); // Name: zergling - Health: 35 | |
// Clever case | |
var terran = { | |
name: "marine", | |
health: 45 | |
}; | |
terran.reportStatus = zerg.reportStatus; | |
terran.reportStatus(); // Name: marine - Health: 45 | |
// Surprising case | |
var button = document.createElement('button'); | |
button.onclick = zerg.reportStatus; | |
// OR | |
$('button').click(zerg.reportStatus); | |
button.onclick(); | |
// When clicked, we get "Name: - Health: undefined" | |
// It tried to look for button's name, not the zerg's. | |
// Ridiculous case | |
var statusReporter = zerg.reportStatus; | |
statusReporter(); | |
// When clicked, we get "Name: - Health: undefined" | |
// It tried to look for window's name. | |
// What you actually wanted | |
var statusReporter = function() { | |
zerg.reportStatus(); | |
} | |
statusReporter(); | |
// Name: zergling - Health: 35 | |
// Shorthand for the above (in modern JS engines) | |
var statusReporter = zerg.reportStatus.bind(zerg); | |
statusReporter(); // zerg's info | |
var terranReporter = zerg.reportStatus.bind(terran); | |
terranReporter(); // terran's info | |
//Two ways to work around "this" not pointing to what you expect: | |
// anon function | |
function() { | |
zerg.reportStatus(); | |
} | |
// bind() | |
zerg.reportStatus.bind(zerg); | |
// The inner function case | |
var zerg = { | |
name: "zergling", | |
health: 35, | |
reportStatusSlowly: function() { | |
//var self = this; | |
var nameChars = this.name.split(""); // [z, e, r, g, l, i, n, g] | |
console.log("My name is: "); | |
nameChars.forEach(function(letter) { | |
console.log(letter + " - health: " + this.health); | |
}); | |
} | |
}; | |
zerg.reportStatusSlowly(); | |
// Problem: this in the inner function != zerg | |
Exercise: http://ejohn.org/apps/learn/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment