javascript - understanding this keyword

this keyword

articles

understanding-the-this-keyword-in-javascript : toddmotto.com

developer.mozilla.org

Tests, closures and arrow functions : glebbahmutov.com

this keyword in JavaScript will burn you one day. Then it will burn you again and again and again. If Dante Alighieri were alive today, he would put writing object-oriented JavaScript among one of the first levels of Hell for sure.

'this' in TypeScript - TypeScript/wiki

code demo

Every new function defined its own this value :

function Person() {
  // The Person() constructor defines `this` as an instance of itself.
  this.age = 0;
  this.printAge = function () {
    console.log(this.age);
  };

  setInterval(function growUp() {
    // In non-strict mode, the growUp() function defines `this` 
    // as the global object, which is different from the `this`
    // defined by the Person() constructor.
    this.age++;
  }, 1000);
}

var p = new Person();
p.printAge(); // 0

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

function Person() {
  var that = this;
  that.age = 0;
  that.printAge = function () {
    console.log(this.age);
  };


  setInterval(function growUp() {
    // The callback refers to the `that` variable of which
    // the value is the expected object.
    that.age++;
  }, 1000);
}

var p = new Person();
p.printAge(); // 0 then ++ each second

In ECMAScript 6, an arrow function does not create its own this, the this value of the enclosing execution context is used.

function Person(){
  this.age = 0;
  this.sayAge = function () {
    console.log(this.age);
  };

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();
p.sayAge(); // 0 then ++ each second

results for ""

    No results matching ""