DEV Community

Cover image for Polyfill for call in JavaScript
Santosh Bharti
Santosh Bharti

Posted on

1

Polyfill for call in JavaScript

What is Function.prototype.call?

The call method allows you to invoke a function with a specified this context and pass arguments individually. Here’s a quick example:

Image description

How we can Implement custom call

Image description

Setting Default Context:

context = context || globalThis;

  • If context is null or undefined, it defaults to globalThis. This ensures the function is called in the global context when no context is provided.

Creating a Unique Key:

const uniqueKey = Symbol("fn");

  • A Symbol is used to create a unique property key to avoid overwriting existing properties on the context object.

Assigning the Function to the Context:

context[uniqueKey] = this;

  • The function (this refers to the function being called) is temporarily added as a property of the context object.

Calling the Function:

const result = context[uniqueKey](...args);

  • The function is called with the provided arguments using the spread syntax.

Cleaning Up:

delete context[uniqueKey];

  • The temporary property is removed from the context object to prevent side effects.

Returning the Result:

return result;

  • The result of the function call is returned.

Top comments (1)

Collapse
 
karishma_cdd733401f9d48d4 profile image
Karishma

👍

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay