custom bind method
write a polyfill for bind method
- takes "this"/"context" as first as argument and other parameter along with
- returns a function , this function can also accepts parameter
Function.prototype.myBind = myBind;
function myBind(context, ...args) {
if (typeof this !== "function") {
throw new Error(this + "call is okacdsc not a function");
}
let callingFunction = this;
// return function
// return ()=>{
// // this value will be from parent scope. because it is arrow function
// console.log("my ",this) // this here is function (callingFunction)
// this.call(context,[...args])
// }
return function (...newArgs) {
// this value will be from parent scope. because it is arrow function
console.log("my ", this); // here this will depend on where it is calling
callingFunction.apply(context, [...args, ...newArgs]);
};
}
function abc(...args) {
console.log("this", this);
console.log("args", args);
}
const a = {
name: "Shadab",
};
let newabc = abc.myBind(a, 1, 2, 3);
// This will trigger the error
newabc(4, 5, 6);