How to Pass this Keyword to a Function Using JavaScript

Shiv Yadav Feb 02, 2024
  1. Use the call() and apply() Methods in JavaScript
  2. Use the bind() Method in JavaScript
How to Pass this Keyword to a Function Using JavaScript

The this keyword is a crucial idea in JavaScript. In JavaScript, this is a handle to an object.

The object that this relates to can alter, intuitively, based on whether it is public, on an entity, or in a constructor. It can also vary expressly depending on the amount of the function concept procedures bind, call, and apply.

In this tutorial, you’ll discover what the this keyword relates to intuitively relying on context, and you’ll discover how to use bind, call, and apply methods to identify the value of this directly.

Use the call() and apply() Methods in JavaScript

Both call() and apply() do the same thing: they call a function given this context and optional parameters. The only contrast between the two methods is that call() takes one-by-one arguments, whereas apply() accepts an array of arguments.

In this example, we’ll make an object and a function that refers to it but doesn’t have any this context.

Example:

const fruit = {
  name: 'Apple',
  location: 'Nepal',
} function summ() {
  console.log(`${this.name} is found in ${this.location}.`)
} summ()

Output:

"result is found in https://fiddle.jshell.net/_display/?editor_console=true."

Because summ and fruit are unrelated, executing summ by itself will be undefined as the global object searches for those properties. You can, however, use call and apply to invoke this fruit context on the method.

const fruit =
    {
      name: 'Apple',
      location: 'Nepal',
    }

    function summ() {
      console.log(`${this.name} is found in ${this.location}.`)
    }

    summ.call(fruit)

Run Code

const fruit =
    {
      name: 'Apple',
      location: 'Nepal',
    }

    function summ() {
      console.log(`${this.name} is found in ${this.location}.`)
    }

    summ.apply(fruit)

Run Code

Output:

"Apple is found in Nepal."

There is now a link between the fruit and the summ when these strategies are used. Let’s make sure we’re on the same page and know what this is.

function printhis() {
  console.log(this)
}
printhis.call(fruit)

Run Code

function printhis() {
  console.log(this)
}
printhis.apply(fruit)

Run Code

Output:

{
  location: "Nepal",
  name: "Apple"
}

The this is the object supplied as an argument in this scenario. call() and apply() are similar in this way, but there is one minor distinction.

You can optionally pass extra parameters in addition to this context as the first argument. With the call() method, each additional value you want to pass is submitted as a separate argument.

const fruit =
    {
      name: 'Apple',
      location: 'Nepal',
    }

    function longerSumm(family, year) {
      console.log(`${this.name} is found in ${this.location}. It is from ${
          family} family found in ${year}.`)
    }

    longerSumm.call(fruit, 'malius', 1900)

Run Code

Output:

"Apple is found in Nepal. It is from malius family found in 1900."

If you send the same arguments with apply(), this happens.

const fruit =
    {
      name: 'Apple',
      location: 'Nepal',
    }

    function longerSumm(family, year) {
      console.log(`${this.name} is found in ${this.location}. It is from ${
          family} family found in ${year}.`)
    }

    longerSumm.apply(fruit, 'malius', 1932)

Run Code

Output:

Uncaught TypeError: CreateListFromArrayLike called on non-object

Instead, you must pass all of the arguments in an array to apply().

const fruit =
    {
      name: 'Apple',
      location: 'Nepal',
    }

    function longerSumm(family, year) {
      console.log(`${this.name} is found in ${this.location}. It is from ${
          family} family found in ${year}.`)
    }

    longerSumm.apply(fruit, ['malius', 1900])

Output:

"Apple is found in Nepal. It is from malius family found in 1900."

Run Code

The difference between passing arguments individually and in an array is slight. Using apply() could be easier because it doesn’t require modifying the function call if any argument details change.

Use the bind() Method in JavaScript

You may need to call a method with the this context of another object repeatedly, in which case you can use the bind() method to construct a new function with an intentionally linked this.

const fruit = {
  name: 'Apple',
  location: 'Nepal',
} function summ() {
  console.log(`${this.name} is found in ${this.location}.`)
} const newSummary = summ.bind(fruit)
newSummary()

Output:

"Apple is found in Nepal."

Run Code

When you call newSummary in this example, it will always return the original value tied to it. It will fail if you try to tie a new this context to it.

Thus, you can always rely on a linked function to provide the this value you expect.

const fruit = {
  name: 'Apple',
  location: 'Nepal',
} function summ() {
  console.log(`${this.name} is found in ${this.location}.`)
} const newSummary = summ.bind(fruit)
newSummary()

const fruit2 = {
  name: 'Mango',
  location: 'Terai',
}
newSummary.bind(fruit2)
newSummary()

Output:

"Apple is found in Nepal."

Run Code

Even though this example attempts to bind newSummary a second time, it keeps the original context from the first time it was bound.

Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn