Lexical This Scope
// ES5
var obj = {
name: "Hemant",
actions: ["Dance", "Sing", "Swim", "Run"],
displayAction: function(){
var self = this;
this.actions.forEach(function(action){
console.log(self.name + " can "+ action);
});
}
}
obj.displayAction();
// OR
var obj = {
name: "Hemant",
actions: ["Dance", "Sing", "Swim", "Run", "Eat"],
displayAction: function(){
this.actions.forEach(function(action){
console.log(this.name + " can "+ action);
}.bind(this));
}
}
obj.displayAction();
this with arraow function referes to parent scope
var btn = document.querySelector('.btn');
btn.addEventListiner('click', function(){
console.log(this); // this referes to button clicked on
});
btn.addEventListiner('click', () => {
console.log(this); // this referes to window
});
btn.addEventListiner('click', function() => {
console.log(this); // this referes to button
setTimeout(() => {
console.log(this); // button, as in arrow function this referes to parent scope
})
});
this with ES6 arrow function
var obj = {
name: "Hemant",
actions: ["Dance", "Sing", "Swim", "Run"],
displayAction: function(){
this.actions.forEach(action => console.log(this.name + " can "+ action));
}
}
obj.displayAction();
Last updated
Was this helpful?