0

In the following example:

const Auth = {
  token : null,

  setToken: (newToken) =>{
   Auth.token = newToken
  },

  getToken : () =>{
    return Auth.token
  },
  
  getTokenViaThis: () =>{
    return this.token
  },
  
  setTokenViaThis: (newToken) =>{
    this.token = newToken
  }
}

Auth.setToken('hello')
Auth.setTokenViaThis('howdy')

console.log(Auth)

Auth.token = "hello" --> I would expect it to be "howdy"

Can someone explain what's the difference between setting a property on an object via objectName.property vs this.property. Because the setTokenViaThis is using an arrow function, I would expect the this to refer to the Auth object itself and behave the same way as Auth.token. It seems I'm missing something important here.

Antuan
  • 501
  • 2
  • 6
  • 18
  • 1
    *"Because the setTokenViaThis is using an arrow function, I would expect the this to refer to the Auth object"* — Why? That's explicitly *not* how arrow functions work. `this` inside an arrow function is whatever `this` was where that object was declared. – deceze Jun 11 '21 at 07:01
  • 1
    `Auth.token` and `this.token`, are not equivalent.. You have not created a class, so `this` is the global object. – Keith Jun 11 '21 at 07:04
  • After reading the post @deceze shared, it seems that this does not refer to the object, but to something else, the window? Not sure – Antuan Jun 11 '21 at 07:07

0 Answers0