If we implement polyfill of call, it will attach fn to the person1 object, so we need to delete that property manually after calling that function delete obj.fn
Great video bro, keep doing videos like this. One small thing you missed is that you are adding a function to the object but not deleting it. Make sure to remove function from the object after the function call is done
very helpfull content, One place for all polyfill questions. thankyou Akash. for apply , this code is working fine with list of array Function.prototype.myApply = function (obj = {}, args) { if (typeof this !== "function") { throw new Error("Not callable"); } if (!Array.isArray(args)) { throw new Error("CreateListFromArrayLike called on non-object"); } obj.fn = this; obj.fn(...args); }; please let know if its helpfull
Bro please correct me if I am wrong, but the polyfill for apply is not correct, cause in obj.fn(...args), in this ...args will give an array, and thus, if you run this code for more than arguments passed in array for myapply method then it will treat the whole ...args in obj.fn(...args), as one argument and thus treat it same way, I am attaching my code please see it, and if I am making some mistake please correct me. let obj1 = { name: 'Name1' } let obj2 = { name: "Name2" } function printInfo(age, year) { console.log(`He is ${this.name} and he is ${age}, and ${year} born`) } Function.prototype.myApply = function(obj = {}, ...args) { // we should use args here instead of ...args, all other things will work if(typeof this !== 'function') throw new Error('Not Applyable') if(!Array.isArray(...args)) throw new Error('TypeError: CreateListFromArrayLike called on non-object') console.log(' ...args', ...args); // this will print [28, 1995] obj.fn = this; obj.fn(...args); } printInfo.apply(obj2, [28, 1995]); // it will print: "He is name2 and he is 28, and 1995 born" printInfo.myApply(obj1, [28, 1995]); // it will print: "He is name1 and he is 28,1995, and undefined born"
Yeah this is true. One thing i did different was use the flat method on the args array before passing it into the function. That way, we are sure the passed args are a single depth array and hence wouldn't throw the above error. Let me know if my approach is wrong or can be improved.
@@sudiptapradhan6101yes that's right but we can also avoid to use rest parameter instead of it we can simply take a parameter which will stored array . So we can skip from flat method