DEV Community

Cover image for Polyfill for Apply()
Chiranjit Dey
Chiranjit Dey

Posted on

Polyfill for Apply()

Polyfills are essential tools for developers aiming to create web applications compatible with a wide range of browsers. These code snippets bridge the gap between modern functionalities and older browser limitations.

Today, we'll delve into the apply() function and explore how to implement a polyfill for it, ensuring your applications function seamlessly across different browser environments.

Given below is a line by line explanation of the code.

  1. The apply() method in JS invokes a function with a specified "this" value and allows passing arguments in an array.

  2. Ln:1, person is an object.

  3. Ln:5, printAge is a function, that takes age as an arg. (Apply method can take N number of arguments in the array).

Polyfill for Apply

  1. Ln:9, Function.prototype.myApply is our polyfill that handles the apply method. It takes the object and [arguments].

  2. Ln:11, we check whether the typeOf "this" and typeOf the ...args, if both satisfies then,

  3. Ln:10, we make a key in the object naming it fn and assigning "this" to it. "this" refers to the printAge function() here.

  4. Ln:19 we call the function with the arguments.

  5. Ln:22, we call the myApply method here and get to see our output in the console.

If you like the post, let's connect on Twitter or LinkedIn. I post almost everyday about JS fundamentals.

Twitter
LinkedIn

Top comments (0)