Table of contents
1.
Introduction
2.
What is call apply and bind in JavaScript?
3.
What is a Polyfill in JavaScript?
4.
The Call() Method
4.1.
Syntax
4.2.
Example
4.3.
JavaScript
5.
Writing Our Own Call Polyfill
5.1.
Example
6.
Apply() Method in Javascript
6.1.
Syntax
6.2.
Example
7.
Writing Our Own Apply Polyfill
7.1.
Example
8.
Bind() Method in Javascript
8.1.
Syntax
9.
Writing Our Own Bind Polyfill
9.1.
Example
9.2.
Example of bindObj After Running bindObj.myMethod = this
9.3.
Example of Bind Polyfill with Parameters
9.4.
JavaScript
10.
Frequently Asked Questions 
10.1.
What is the difference between call() and apply()?
10.2.
When should I use a polyfill?
10.3.
Can I use polyfills for any JavaScript feature?
10.4.
What does call () do?
10.5.
Why bind is required in JavaScript?
10.6.
What is the use of bind () system call?
11.
Conclusion
Last Updated: Oct 7, 2024
Easy

Call apply bind in Javascript

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In web development, JavaScript remains a main player, which still consistently introduces new features like `call`, `apply`, and `bind`. These functions enhance the flexibility and control developers have over the execution context of functions. However, the main challenge is that not every user's browser keeps pace with these updates. To solve this challenge, developers use polyfills in JavaScript. These polyfills provide compatibility for `call`, `apply`, and `bind` methods, which ensures that even older browsers can support modern JavaScript functionalities without requiring users to update their software.

Call apply bind in Javascript

What is call apply and bind in JavaScript?

In JavaScript, `call`, `apply`, and `bind` are methods used to control the execution context of functions—the value of `this` inside the function.

  • call(): This method calls a function with a specified `this` value and individual arguments. For example, `func.call(thisValue, arg1, arg2)`.
  • apply(): Similar to `call`, but arguments are passed as an array, making it ideal when the number of arguments is not fixed. Use it like `func.apply(thisValue, [arg1, arg2])`.
  • bind(): This method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. For instance, `const newFunc = func.bind(thisValue, arg1, arg2)`.

What is a Polyfill in JavaScript?

A polyfill is essentially a fallback mechanism. It detects if a certain feature is missing in the browser's JavaScript engine and manually implements it. Developers can thus use the latest features without excluding users on outdated browsers. Polyfills are not part of the JavaScript specification; they are community-driven solutions for bridging the gap between the new and the old.

The Call() Method

The call() method calls a function with a given value and arguments provided individually.

Syntax

func.call(thisArg, arg1, arg2, ...argN);

Example

  • JavaScript

JavaScript

function greet() {

 let reply = [this.animal, 'typically sleep', this.sleepDuration].join(' ');

 console.log(reply);

}

let obj = {

 animal: 'cats',

 sleepDuration: '12 and 16 hours'

};

greet.call(obj); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Output

In this example, call() is used to invoke the greet function in the context of obj, allowing us to use the properties of obj within the greet function.

Writing Our Own Call Polyfill

Creating a call polyfill involves adding a method to Function.prototype that can invoke a function with a specified this context and arguments.

Example

Function.prototype.myCall = function(context, ...args) {
  context = context || global;
  let func = this;
  context.fn = func;
  let result = context.fn(...args);
  delete context.fn;
  return result;
};

Apply() Method in Javascript

The apply() method is similar to call(), but instead of taking arguments individually, it takes them as an array.

Syntax

func.apply(thisArg, [argsArray]);

Example

function saySomething(phrase) {
  console.log(this.name + ' says ' + phrase);
}
let person = {
  name: 'Cristiano'
};
saySomething.apply(person, ['hello']); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Cristiano says hello


In the saySomething example, apply() allows us to call the function with person as the context and pass an array of arguments.

Writing Our Own Apply Polyfill

An apply polyfill can be created by modifying our myCall polyfill to accept an array of arguments.

Example

Function.prototype.myApply = function(context, args) {
  context = context || global;
  let func = this;
  context.fn = func;
  let result;
  if (args) {
    result = context.fn(...args);
  } else {
    result = context.fn();
  }
  delete context.fn;
  return result;
};

Bind() Method in Javascript

The bind() method in JavaScript allows you to create a new function with this keyword set to the provided value, with a given sequence of arguments preceding any others when the new function is called.

Syntax

let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]]);


Example 1:

let obj = {

 x: 42,

 getX: function() {

  return this.x;

 }

};

let unboundGetX = obj.getX;

console.log(unboundGetX()); // The function gets invoked at the global scope
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

undefined

 

Example 2:

let obj = {

 x: 42,

 getX: function() {

  return this.x;

 }

};

let unboundGetX = obj.getX;

console.log(unboundGetX()); // The function gets invoked at the global scope


let boundGetX = unboundGetX.bind(obj);

console.log(boundGetX());
You can also try this code with Online Javascript Compiler
Run Code


Output: 

undefined
42


In the example above, bind() is used to bind the this context of the getX method to the obj object, ensuring that it does not lose context when called independently.

Writing Our Own Bind Polyfill

To create a bind polyfill, we extend the Function.prototype to include a method that can bind a context to a function.

Example

Function.prototype.myBind = function(context, ...args) {
  let func = this;
  return function(...newArgs) {
    return func.apply(context, [...args, ...newArgs]);
  };
};

 

Explanation of Code

The myBind method takes a context object and additional arguments. It returns a new function that, when called, has its this keyword set to the provided context, with the initial arguments followed by the new ones.

Example of bindObj After Running bindObj.myMethod = this

let bindObj = {
  myMethod: function() {
    console.log(this);
  }
};
bindObj.myMethod = bindObj.myMethod.myBind(obj);
bindObj.myMethod(); // Logs the `obj` context to the console

Example of Bind Polyfill with Parameters

  • JavaScript

JavaScript

let name = {

 firstName: "Cristiano",

 lastName: "Ronaldo"

};



function printFullName(homeTown, state) {

 console.log(this.firstName + " " + this.lastName + ", " + homeTown + ", " + state);

}



let printMyName = printFullName.myBind(name, "New York");

printMyName("NY");
You can also try this code with Online Javascript Compiler
Run Code

 

Output 

Cristiano Ronaldo, New York, NY
You can also try this code with Online Javascript Compiler
Run Code

Frequently Asked Questions 

What is the difference between call() and apply()?

call() takes arguments separately, while apply() takes arguments as an array.

When should I use a polyfill?

Use a polyfill when you need to support a JavaScript feature that is not available in the current user's browser.

Can I use polyfills for any JavaScript feature?

While many features can be polyfilled, some newer features may rely on browser internals that cannot be replicated with JavaScript alone.

What does call () do?

The call() method in JavaScript allows you to invoke a function with a specified this context and arguments passed individually.

Why bind is required in JavaScript?

The bind() method is used to permanently set the this value for a function, ensuring it retains the correct context during execution.

What is the use of bind () system call?

In operating systems, the bind() system call associates a socket with a local address (IP, port) to ensure the socket communicates through the specified endpoint.

Conclusion

Polyfills are an essential tool in a web developer's arsenal, allowing for the use of modern JavaScript features while maintaining compatibility with older browsers. By understanding and implementing polyfills, developers can ensure that their applications are accessible to a wider audience without sacrificing functionality or performance. With the examples and explanations provided, you should now have a solid understanding of how to use and create polyfills for bind(), call(), and apply() methods in JavaScript.

You can refer to our guided paths on the Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass