Leonardo
Leonardo

Reputation: 303

JavaScript "this" keyword and arrow function

Here this keyword which is in arrow function points to obj's variable environment

var greeting = 'hi';

const obj = {
  greeting: 'hey',

  fo() {
    const greeting = 'hola';
    
      const arrowFo = () => {
        console.log(this.greeting);
      };

      arrowFo();
  },
};

obj.fo(); //logs: hey
but in this new example it points to global object. I did not figure out what has changed? there is just added a new regular function fo2. Can anyone explain to me what is happening there? (I was anticipating that it would pointed to fo2's local environment and would printed "hello") Thanks in advance

var greeting = 'hi';

const obj = {
  greeting: 'hey',

  fo() {
    const greeting = 'hola';

    const fo2 = function () {
      const greeting = 'hello';

      const arrowFo = () => {
        console.log(this.greeting);
      };

      arrowFo();
    };
    fo2();
  },
};

obj.fo(); //logs: hi

Upvotes: 9

Views: 10078

Answers (2)

Belhadjer Samir
Belhadjer Samir

Reputation: 1659

In JavaScript the this object is really based on how you make your function calls. the fo2() function is not binded in any object for this purpos it get the this of global context

you have to declare your function with the this like this :

var greeting = 'hi';

const obj = {
  greeting: 'hey',

  fo() {
    const greeting = 'hola';

     this.fo2 = function () {
      const greeting = 'hello';

      const arrowFo = () => {
        console.log(this.greeting);
      };

      arrowFo();
    };
    this.fo2();
  },
};

obj.fo(); //logs: hi

or use arrow function like this :

var greeting = 'hi';
const obj = {
  greeting: 'hey',
  fo() {
    const greeting = 'hola';
    fo2 =  () => {
      const greeting = 'hello';
      const arrowFo = () => {
        console.log(this.greeting);
      };
      arrowFo();
    };
    fo2();
    
  },
};
obj.fo();

Upvotes: 2

Ahmetcan OZCAN
Ahmetcan OZCAN

Reputation: 136

Arrow functions have no this value in their scope, so you can access this value of the object. But Normal functions have this value in their scope, in this example this value of the normal function is globalThis or window. and it allows to you access the global scope. if you call fo2 with this value of object instead of globalThis you get '"hey"'

var greeting = 'hi';

const obj  = {
  greeting: 'hey',

  fo() {
    const greeting = 'hola';

    const fo2 = function () {
      const greeting = 'hello';

      const arrowFo = () => {
        console.log(this.greeting);
      };

      arrowFo();
    };
    fo2.call(this) // Use this instead of fo2()
  },
};


Upvotes: 8

Related Questions