DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

 

Determine this in JS

this is determined by how a function is called, not how it is defined.

Things to find this:

  • When a function is called as a method of an object, this refers to the object itself.
  • When a function is called without a context, this refers to the global object in non-strict mode, or to undefined in strict mode.
  • When a function is called with the new keyword, this refers to a newly created object that inherits from the function's prototype.
  • When a function is called with call or apply, this is explicitly set to the first argument passed to call or apply.
  • Arrow functions do not have their own this value, but instead inherit this from the surrounding scope.
  • The bind method can be used to create a new function that has a specific this value.

Example

As a method of an object:

const person = {
  name: 'John',
  sayHello() {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.sayHello(); // logs "Hello, my name is John!"
Enter fullscreen mode Exit fullscreen mode

In a regular function:

function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

sayHello(); // logs "Hello, my name is undefined!" in non-strict mode, or throws an error in strict mode
Enter fullscreen mode Exit fullscreen mode

With the new keyword:

function Person(name) {
  this.name = name;
}

const john = new Person('John');
console.log(john.name); // logs "John"
Enter fullscreen mode Exit fullscreen mode

With call or apply:

function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

const person = {
  name: 'John'
};

sayHello.call(person); // logs "Hello, my name is John!"
Enter fullscreen mode Exit fullscreen mode

In an arrow function:

const person = {
  name: 'John',
  greet: () => {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.greet(); // logs "Hello, my name is undefined!" since arrow functions do not have their own `this` value
Enter fullscreen mode Exit fullscreen mode

With bind:

const person = {
  name: 'John'
};

function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

const sayHelloToPerson = sayHello.bind(person);
sayHelloToPerson(); // logs "Hello, my name is John!"

Enter fullscreen mode Exit fullscreen mode


`

Top comments (0)

Visualizing Promises and Async/Await šŸ¤Æ

async await

Learn the ins and outs of Promises and Async/Await!