Skip to content

Why this

Posted on:June 14, 2023 at 09:06 AM
const a = {
	count: 1,
	func: function() {
	 	console.log(this.count)
	}
}


a.func()

const b = {
	count: 1,
	func: () =>  {
	 	console.log(this.count)
	}
}


b.func()

this, current scope

During a simple invocation the value of this equals the global object (or undefined if the function runs in strict mode):

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

// Simple invocation
myFunction(); //

his value inside the arrow function callback() equals this of the outer function myMethod().

this resolved lexically is one of the great features of the arrow functions. When using callbacks inside methods you are sure the arrow function doesn’t define its own this (no more const self = this or callback.bind(this) workarounds).

Contrary to a regular function, the indirect invocation of an arrow function using myArrowFunc.call(thisVal) or myArrowFunc.apply(thisVal) doesn’t change the value of this: the context value always resolves lexically.

const myObject = {
  myMethod(items) {
    console.log(this); // logs myObject
    const callback = () => {
      console.log(this); // logs myObject
    };
    items.forEach(callback);
  }
};

myObject.myMethod([1, 2, 3]);
use 'scrict mode'
const myObject = {
  myMethod: function(items) {
    console.log(this); // logs myObject
    const callback = function() {
      console.log(this); // logs myObject
    };
    items.forEach(callback);
  }
};

myObject.myMethod([1, 2, 3]);
Type ".help" for more information.
> const myObject = {
...   myMethod: function(items) {
...     console.log(this); // logs myObject
...     const callback = function() {
...       console.log(this); // logs myObject
...     };
...     items.forEach(callback);
...   }
... };
undefined
<ref *1> Object [global] {
  global: [Circular *1],
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  structuredClone: [Function: structuredClone],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  atob: [Function: atob],
  btoa: [Function: btoa],
  performance: Performance {
    nodeTiming: PerformanceNodeTiming {
      name: 'node',
      entryType: 'node',
      startTime: 0,
      duration: 605.8705299980938,
      nodeStart: 5.811547998338938,
      v8Start: 9.775522001087666,
      bootstrapComplete: 38.022973999381065,
      environment: 22.135492999106646,
      loopStart: 64.12841499969363,
      loopExit: -1,
      idleTime: 501.496411
    },
    timeOrigin: 1687499299936.869
  },
  fetch: [AsyncFunction: fetch]
}