Created
February 10, 2017 05:21
-
-
Save andrescabana86/80ae303d9cbb079fb6f93f800e94f484 to your computer and use it in GitHub Desktop.
Context "this" in EMAC2015
This file contains hidden or 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
//exec with node.js | |
this.me = 'context file:'; | |
var names = ["José", "Alfredo", "Ernesto"]; | |
var person = { | |
me: 'context person:', | |
greet: function () { | |
names.forEach(function (name) { | |
console.log(this.me, 'saying hello to', name); // this print: undefined saying hello to ${name} | |
}); | |
} | |
}; | |
person.greet(); // the context of this is an anonimous function this==function | |
var person = { | |
me: 'context person:', | |
greet: function () { | |
names.forEach((name) => { // arrow function passes the parent context (person) to the anonymous function | |
console.log(this.me, 'saying hello to', name); // this print: context person: saying hello to ${name} | |
}); | |
} | |
}; | |
person.greet(); // the context of this is the person class this==person.js | |
var person = { | |
me: 'context person:', | |
greet: () => { // arrow function passes the parent context to the person context | |
names.forEach((name) => { // arrow function passes the parent context to the function (from the parent) | |
console.log(this.me, 'saying hello to', name); // this print: context file: saying hello to ${name} | |
}); | |
} | |
}; | |
person.greet(); // the context of this is the file this==context-this.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment