Arrow Function and 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 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