0

Why in both examples an empty object is being printed out? In the first example, should this be equal to the global environment? Also, in the second example, I've used an arrow function to bind this to obj2 object, so I expected x() to return the obj2 object, but got an empty object instead? Can someone please explain what's going on here.

let obj1 = {
  name: "object1",
  method: function(a) {
    console.log(a)
  }
}
obj1.method(this)

// ---------------------
let obj2 = {
  name: "object2",
  method: () => {
    console.log(this)
  }
}
let x = obj2.method;
x()
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • "Also, in the second example, I've used an arrow function to bind this to obj2 object" — No, you haven't. You've bound it to the `this` value in the function you put the object literal in. – Quentin Jan 13 '19 at 20:10
  • 1
    "Why in both examples an empty object is being printed out?" — They don't. – Quentin Jan 13 '19 at 20:10
  • this is because obj.method is a function, not an object. may be you wanted to do `let x = obj2.method();` ? – Dimitri L. Jan 13 '19 at 20:11
  • @DimitriL. — That would be `undefined` and `x()` would throw an error. – Quentin Jan 13 '19 at 20:11

1 Answers1

0

In the first example, should this be equal to the global environment?

Depends on where you’re running it. I’m going to assume it’s a Node module, in which case the answer is “no”. this is set to the module’s exports:

console.log(this === global);  // false
console.log(this === module.exports);  // true

in the second example, I've used an arrow function to bind this to obj2 object, so I expected x() to return the obj2 object, but got an empty object instead

No, the rule for arrow functions is that this means the same thing inside them as it does outside. The presence of an object literal doesn’t affect that.

Ry-
  • 218,210
  • 55
  • 464
  • 476