Search code examples
javascriptconstructorthisarrow-functionsobject-literal

ES6 Arrow function: why "this" points differently when used in constructor and object literal?


I know that arrow functions inherit this from enclosing scope. Yet, still can't understand why this in arrow function defined in object literal points to global object, while in constructor to created object. Consider following code:

function Obj() {
  this.show = () => {
    console.log(this);
  };
}
const o = new Obj();
const o2 = {
  show: () => {
    console.log(this);
  }
}

o.show(); // o
o2.show() // window || undefinded

Solution

  • function Obj() {
      this.show = () => {
        console.log(this);
      };
    }
    const o = new Obj();
    o.show(); 
    

    Here "this" works based on the rules of the "new" keyword, pointing to a new object with the structure defined inside Obj() (the new object is the context). More info at : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

    const o2 = {
      show: () => {
        console.log(this);
      }
    }
    o2.show() // window || undefinded
    

    Here "this" gets its value at runtime and because neither lambda functions nor object literals define a context, the context remaining is the global one and that is why you get that value.