-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
polyfill for Function.prototype.bind()
- Loading branch information
1 parent
6552b26
commit f8d8bf9
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |