0

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

3 Answers3

1

Ok, found the answer, as stated in "Secrets of the javascript ninja":

Arrow functions don't have their own context. Instead, the context is inherited from the function in which they’re defined.

So inside constructor function this === {}. While, when defining object literal this still points to global object or undefined if in strict mode.

1

That's because at the time of declaration the Object is not initialized yet. You can force initialization by using an immediately invoked function expression (IIFFE) or use Object.create. Something like:

// IIFE
const x = (() => ({a: 1, b: 2, sum() {return this.a + this.b}}))();
console.log(`x.sum() => ${x.sum()}`);
// Object.create
const y = Object.create({a:1, b:2, sum() {return this.a + this.b}});
console.log(`y.sum() => ${y.sum()}`);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1
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.

Beto Rodriguez
  • 114
  • 1
  • 3