Skip to content

Instantly share code, notes, and snippets.

@JacobWay
Created December 27, 2016 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacobWay/2330ec2c9831f9fbf531eb23fc4b2908 to your computer and use it in GitHub Desktop.
Save JacobWay/2330ec2c9831f9fbf531eb23fc4b2908 to your computer and use it in GitHub Desktop.
JavaScript code example of this in anonymous, callback, arrow function, es6, es5
{
class Message {
doCallback(cb){
cb("!!");
}
doAnother(){
console.log("??", this); // Message
}
doSomething() {
this.doCallback(function(message){
this.doAnother(); // undefined
})
}
}
(new Message).doSomething();
}
{
class Message {
doCallback(cb){
cb("!!");
}
doAnother(){
console.log("??", this); // Message
}
doSomething() {
this.doCallback((message) => {
this.doAnother(); // this: undefined, but arrow function doesn't create its own this context.
})
}
}
(new Message).doSomething();
}
(function(){
function Message(){
}
Message.prototype = {
doCallback: function(cb){
cb("!!");
},
doAnother: function(){
console.log("??", this); // Message
},
doSomething: function() {
this.doCallback(function(message){
this.doAnother(); // this: Window, so maybe doAnother is undefined
})
}
}
var message = new Message()
message.doSomething();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment