I would like to see some examples/ clarification on how to use .this in ES6 following the arrow function syntax and how its different from ES5 .this binding.
            Asked
            
        
        
            Active
            
        
            Viewed 67 times
        
    0
            
            
        - 
                    2[What does “this” refer to in arrow functions in ES6?](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) – The difference from `.bind(this)` is that you can't remove it and have an unbound arrow function. – Jonathan Lonowski Dec 10 '16 at 03:24
- 
                    See also [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Dec 10 '16 at 08:06
2 Answers
0
            
            
        It's pretty straightforward:
In ES6 you have arrow functions which are "anonymous" in that they have no proper context. Therefore, this refers to the parent context.
In ES5, the equivalent is a function which DOES contain its own context. The way to use this correctly (assuming you want the parent's context) is to bind it like so:
function something() {//}
// invoke
something().bind(this);
 
    
    
        ZekeDroid
        
- 7,089
- 5
- 33
- 59
0
            
            
        Consider the following functions in es5:
        // Scope Problem in es5 :
    var defaultPower = "Laser Vision";
    function superHero() {
      this.defaultPower = "Ice Ray";
      setTimeout(function grantPowers() {
        console.log("Super " + this.defaultPower);
      })
    }
    var IceMan = new superHero();
    // Console logs erroneous "Super Laser Vision"
    // Scope Fix in es5 by using self or _self or that var
    var defaultPower = "Laser Vision";
    function superHero() {
      var self = this;
      self.defaultPower = "Ice Ray";
      setTimeout(function grantPowers() {
        console.log("Super " + self.defaultPower);
      })
    }
    var IceMan = new superHero();
    // Console logs correct "Super Ice Ray"
and in es6:
      // And with arrow functions:
  var defaultPower = "Laser Vision";
  function superHero() {
    this.defaultPower = "Ice Ray";
    setTimeout(() =>  {
      console.log("Super " + this.defaultPower);
    });
  }
  var IceMan = new superHero();
  // Console logs correct "Super Ice Ray"
 
    
    
        Keno
        
- 3,694
- 2
- 21
- 40
