Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Polyfill in JavaScript?
3.
When to Use a Polyfill
3.1.
The Bind() Method
3.2.
Syntax with Parameters
3.3.
JavaScript
3.4.
JavaScript
4.
Writing Our Own Bind Polyfill
4.1.
Example of Our Own Bind Polyfill
4.2.
Example of bindObj After Running bindObj.myMethod = this
4.3.
Example of Bind Polyfill with Parameters
4.4.
JavaScript
5.
The Call() Method
5.1.
JavaScript
5.2.
Writing Our Own Call Polyfill
6.
The Apply() Method
6.1.
Writing Our Own Apply Polyfill
7.
Frequently Asked Questions 
7.1.
What is the difference between call() and apply()?
7.2.
When should I use a polyfill?
7.3.
Can I use polyfills for any JavaScript feature?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Call apply bind in Javascript

Author Rinki Deka
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In the evolving landscape of web development, JavaScript stands as a cornerstone, continually expanding with new features. However, this growth introduces a challenge: not all users' browsers are updated at the same pace.

Call apply bind in Javascript

This is where the concept of a polyfill in JavaScript becomes crucial. A polyfill is a piece of code that provides modern functionality on older browsers that do not natively support it, ensuring a consistent experience across the web.

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

When to Use a Polyfill

Polyfills should be used when there is a need to implement features that are expected to be part of the JavaScript language but are not yet supported by all browsers. Before using a polyfill, it's essential to consider the performance implications and the necessity of the feature for the project.

The Bind() Method

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 with Parameters

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


Detailed Explanation with Working Example

  • JavaScript

JavaScript

let obj = {

 x: 42,

 getX: function() {

   return this.x;

 }

};


let unboundGetX = obj.getX;

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

 output: 

undefined
  • JavaScript

JavaScript

let boundGetX = unboundGetX.bind(obj);

console.log(boundGetX());


output: 

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 of Our Own Bind Polyfill

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

Explanation of Code and Output

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");

Output 

Cristiano Ronaldo, New York, NY

The Call() Method

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

Syntax with Parameters

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


Detailed Explanation with Working 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); 

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 of Our Own Call Polyfill

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;
};

The Apply() Method

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

Syntax with Parameters

func.apply(thisArg, [argsArray]);


Detailed Explanation with Working Example

function saySomething(phrase) {
  console.log(this.name + ' says ' + phrase);
}
let person = {
  name: 'Cristiano'
};
saySomething.apply(person, ['hello']); 

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.

Final Polyfill: Apply Polyfill

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;
};

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.

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 Coding Ninjas. 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.

Previous article
Async Await in Javascript
Next article
Sort Array Of Objects Javascript
Live masterclass