Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "this" keyword and arrow function [duplicate]

Tags:

javascript

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
like image 906
Leonardo Avatar asked May 22 '26 03:05

Leonardo


1 Answers

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()
  },
};


like image 95
Ahmetcan OZCAN Avatar answered May 23 '26 16:05

Ahmetcan OZCAN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!