Skip to content

Commit

Permalink
polyfill for Function.prototype.bind()
Browse files Browse the repository at this point in the history
  • Loading branch information
swarajlaha committed May 29, 2021
1 parent 6552b26 commit f8d8bf9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Day 2/bind.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Polyfill - Function.prototype.bind()
* The bind() 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.
* The below user defined function is a polyfill for the .bind() function, which is predefined in the prototype of Function object.
* myBind() - Returns a function.
*/

let name = {
firstName: "Swaraj",
lastName: "Laha"
};

let printName = function(job, location, country) {
console.log(this.firstName + " " + this.lastName, "works as an " + job + " in " + location + ", " + country);
};

// Function.prototype.bind()
let printMyName = printName.bind(name, "Analyst");
printMyName("Hyderabad", "India"); // O/p: 'Swaraj Laha works as an Analyst in Hyderabad, India'

// Ployfill
Function.prototype.myBind = function(...args) {
let value = this;
let params = args.slice(1); // Returns all elements of array - args, except the 1st element
return function (...argsPloyfill) {
value.apply(args[0], [...params, ...argsPloyfill]);
}
};

// Function.prototype.myBind()
let printMyNamePolyfill = printName.myBind(name, "Analyst");
printMyNamePolyfill("Hyderabad", "India"); // O/p: 'Swaraj Laha works as an Analyst in Hyderabad, India'
8 changes: 8 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<style></style>
<script src="./Day 2/bind.js"></script>
</head>
<body></body>
</html>

0 comments on commit f8d8bf9

Please sign in to comment.