1

I'm having a doubt about the this reference to object and global scope. I know that a method inside an object is refering to the object who contains that function. And that a normal function will refer to the window object. But for some reason it changes depending on how i write it. At least in this code:

this.name = 'global scope'

function log() {
  console.log(this.name);
}

const obj1 = {
  name: 'obj1 scope',
  objlog1: function() {
    console.log(this.name);
  },
  objlog2() {
    console.log(this.name);
  },
  objlog3: log,
  objlog4: function() {
    log()
  },
  objlog5: log()
}

obj1.objlog1(); //obj1 scope
obj1.objlog2(); //obj1 scope
obj1.objlog3(); // obj1 scope
obj1.objlog4(); // global scope
obj1.objlog5 // it executes before i call it for some reason? global scope.

obj1,2,3, is all ok because it marks the obj1 scope. But the obj4 marks the global scope (and it's just a function that calls another function, should be as obj3, right?) and the objlog5 is even executed before I call it (I think it has to be something related to the ()). Sorry if this sounds very 'newbie' question, but I'm having trouble understanding the this.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Aiden
  • 59
  • 4

0 Answers0