Тёмный

Polyfill for bind method | Javascript Interview Questions 

Akshay Saini
Подписаться 1,7 млн
Просмотров 326 тыс.
50% 1

Polyfill for bind function is one of the most important question in frontend javascript interviews. I've faced this question a lot of time while giving interviews and have also started asking this myself while taking interviews.
This video tutorial covers a step by step approach to write our own implementation of bind method in Javascript.
Link to the code - codepen.io/aks...
If you have any suggestions in mind, any topics you want me to discuss or any specific problem, feel free to ping me anytime on LinkedIn, Facebook or just email me directly. I would be happy to help you.
If you find my videos helpful,
then please support this channel by buying a coffee,
www.buymeacoff...
Cheers,
Akshay Saini
akshaysaini.in
Would love to Stay Connected with you ❤️
LinkedIn - / akshaymarch7
Instagram - / akshaymarch7
Twitter - / akshaymarch7
Facebook - / akshaymarch7
#Javascript #JavascriptInterviewQuestions #AkshaySaini

Опубликовано:

 

28 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 281   
@ruchirai5775
@ruchirai5775 4 года назад
@Akshay before this video I went through lot of blogs like medium, stackoverflow to understand binds internal implementation, this is the most easiest and awesome explanation I have ever seen for BIND.Thank you so much :) Can you also make a video on implementing own promise and implementing own virtual DOM ?
@pioneer7161
@pioneer7161 2 года назад
medium pe bass gyaan milta hai.. real life scenario nhi milne wale.. akshay bhai k liye meri taraf se 2 likes
@girishmehra8383
@girishmehra8383 Год назад
@@pioneer7161 bhai 2 likes mat kar ek hi kar 2 karega toh jo ek kiya woh Bhi hat jayega😜😜
@itspravas
@itspravas 5 лет назад
i saw your video on bind, then i saw this one, paused it, tried to do this on my own, got sucess, i haven't used call or apply or any es6 ( like "..." notation )as you said its for older browsers, so yeah i did it, really happy with my result.
@gopalchavan306
@gopalchavan306 5 лет назад
Hi Pravas, can you please share your code, without es6, call and apply
@vikramkrish710
@vikramkrish710 4 года назад
Would like to see the polyfill without call and apply, how do you pass the 'this' binding inside the returning function?
@raveenasharma4645
@raveenasharma4645 3 года назад
Your explanation about basic concepts is so good. I've been watching the entire JS series! Thank you so much
@nihalgupta5430
@nihalgupta5430 Год назад
Prototype ,proptotypal inheritence ,prototype chaining ,call bind apply all i have learnt from you now everything was implemented here and i understood it with utmost efficacy thanks Akshay
@raghavendrasao6959
@raghavendrasao6959 4 года назад
Hi @akshay, u r doing a great job !! i have one small suggestion. in line no 17 i think we can add return before obj.apply(....) also, because if printName will return something then our mybind will return always undefined.
@asitkumar8543
@asitkumar8543 3 года назад
The bind() method creates a new function, when invoked, has the this sets to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
@mdridoy-ef2pw
@mdridoy-ef2pw 2 года назад
Not a even the og youtubers discuss these core topics like you. Thank you! More simpler version of the myBind function: Function.prototype.myBind = function (...args1) { return (...args2) => this.call(...args1, ...args2); }
@aiknowledge-n2s
@aiknowledge-n2s 2 года назад
Function.prototype.myBind = function (...args) { let ref = args[0]; let params = args.slice(1); let obj = this; return function (...args2) { args[0].gt = obj; //This is my impelementation of the bind polyfill, I haven't used apply method over here. args[0].gt(...params, ...args2); }; }; //I have checked it works.
@sandeepa4116
@sandeepa4116 3 года назад
Ultimate explanation Akshay! Really amazing work of helping so many like me out there. God bless you 🙏🏻 "In the interviews, if we don't want to be SHY, then we gotta learn from AkSHAY" 😎
@digvijaysingh9028
@digvijaysingh9028 3 года назад
what a MASTERPIECE :)
@pintzprajapati
@pintzprajapati 2 года назад
Learned first time and wow it was super easy because of your teaching method. thanks bro
@jalluchakri1528
@jalluchakri1528 Месяц назад
Hey ! Thanks for explaining its makes the comfort to learn any concept
@vishalheble
@vishalheble 4 года назад
When its a polyfill for a bind then can we really use apply or call ?
@patni1234561
@patni1234561 3 года назад
This makes sense. As a interview question, it is okay, but what you said is valid. Which browser supports call apply but not bind.
@shaikhshehroz2107
@shaikhshehroz2107 5 лет назад
You are Best.. Very Well Explained.
@santrawebtech35
@santrawebtech35 2 года назад
you are the God of javascript bro love you
@dgroh
@dgroh 3 года назад
give this guy a medal...
@TheUltimateTrainJourney
@TheUltimateTrainJourney 4 года назад
It was kind of complicated but u nailed it easily 😃
@rabahbabaci2342
@rabahbabaci2342 4 года назад
Thank you dude, this was an amazing explanation! Can you please make a video on how to implement the .call( ); method?
@asimsheikh3511
@asimsheikh3511 2 года назад
that was awesome. I am becoming your fan slowly. thank you for this valuable information.
@charans1845
@charans1845 3 года назад
Excellent explanation. Akshay bro u are fav teacher of mine..
@aiswaryaroshith5383
@aiswaryaroshith5383 9 месяцев назад
@Akshay Great explanation. Thank you. You are such a great teacher.😊
@anurao96
@anurao96 2 года назад
Hi Akshay, If we use a Params directly in to the return function then we use obj.call(…args, …params)
@jaydeep405
@jaydeep405 4 года назад
You motivate me. Your teaching skills are fabulous. I learnt a lot by just viewing a few videos of yours 😊 Keep up the good work
@AIEngineering101
@AIEngineering101 2 года назад
Thanks Akshay for explaining it clearly. I think this is the best video I watched on polyfils. I have a small question here, when we are trying to console this inside Function.prototype.myBind it is referring to window and at the same time if we assign it to variable it is referring to binding function printFullName. is this normal behaviour or am I reading it wrong?
@goyalnaman99
@goyalnaman99 3 месяца назад
It would be really interesting if we could make a polyfill for bind without using call/apply.
@priyasuryawanshi1143
@priyasuryawanshi1143 5 месяцев назад
Really very good explanation
@syedminhaj7132
@syedminhaj7132 3 года назад
Hi, Can you also make a video on implementing own promise and implementing own virtual DOM ? @akshay please make on async and await concepts as well.....waiting for it
@himanshuaggarwal8415
@himanshuaggarwal8415 3 года назад
Thanks I understand it completly.
@Rivhoy6ivu7r
@Rivhoy6ivu7r 3 года назад
pura hindi jaisa lagta h..nice
@ram_pande8039
@ram_pande8039 3 года назад
explained with simplicity. awesome content.
@AryanGNU
@AryanGNU 10 месяцев назад
I have small doubt, since we are writing pollyfill for browsers that don't have bind function won't they also won't have call/apply function also. In that case how is this implementation going to work. I know this is a bit stupid question but please kindly reply 🙏
@candy9193
@candy9193 4 месяца назад
Later u can implement for call too, here we had an example for bind
@mdmobashirraza3117
@mdmobashirraza3117 Год назад
@Akshay Instead of using `slice` I have used `rest operator` to extract the rest of the value from the args. let name = { firstname: 'John', lastname: 'Doe', } let printFullName = function (hometown, state, country) { console.log(this.firstname + ' ' + this.lastname + hometown + ' ' + state + ' ' + country) } Function.prototype.myBind = function (...args) { // `this` -> printFullName let obj = this; const [a, ...b] = args; //rest operator //console.log(a, b) return function (...args2) { //console.log(args2) obj.apply(a, [...b, ...args2]) } } let printMyName2 = printFullName.myBind(name, "Kolkata", "West Bengal"); printMyName2("India");
@codingwithgraceandtruth2456
@codingwithgraceandtruth2456 2 года назад
excellent example and teaching.
@anantanujdey3642
@anantanujdey3642 4 года назад
Thank You Akshay for this lovely explanation.
@vishalbisht6871
@vishalbisht6871 5 лет назад
AWESOME !!!!
@NaveenRawat51
@NaveenRawat51 5 лет назад
you got subscriber++. thank you Akshay the video is awesome
@pratapdessai6687
@pratapdessai6687 3 года назад
@akshay Saini Thanks for this answer. Could you add video for implementing Two way data binding .
@garimabansal681
@garimabansal681 2 года назад
Awesome work
@muiz864
@muiz864 5 лет назад
Nicely explained. Just wondering if interviewer will be okay with a polyfil for bind that uses apply internally. I mean call, bind and apply fall into a common category. Also, a browser that supports ES6 spread operator would also support bind.
@TheNerdyDev
@TheNerdyDev 5 лет назад
Simply Awesome.
@arvindbarala4525
@arvindbarala4525 5 лет назад
sir please also make video for call and apply method
@MohitKumar-tn1cf
@MohitKumar-tn1cf 4 года назад
It's really good !! Can you make a video for own call method please and also have one problem in Javascript.
@harshulkansal
@harshulkansal 3 года назад
Awesome work man! keep it up! really helped me through. :)
@aiknowledge-n2s
@aiknowledge-n2s 2 года назад
Nice work.
@ipsitapanda5764
@ipsitapanda5764 3 года назад
Thanks for the beautiful explanation... @everyone :any suggestions on angular 9 learning video please
@nice.hemant
@nice.hemant Год назад
I am beginner and first time I have seen your JavaScript video but I am confused from which video I start? there so many playlist with same videos. May be I am wrong but plz you suggest me from which channel I start as a beginner.
@tdvkiran
@tdvkiran 4 года назад
concept explained very clearly. Thanks :) , gotta learn alot from you
@RavindraSingh-zg9eq
@RavindraSingh-zg9eq Год назад
nice great helpful
@tejasmalani9309
@tejasmalani9309 4 года назад
Good explaination bro ..... keep it up ! 👌
@KnownTechnical
@KnownTechnical 4 года назад
Kindly update more videos on core javascript fundamentals
@nitisha1492
@nitisha1492 5 лет назад
Awesome as always
@shreedevijamakhandi1877
@shreedevijamakhandi1877 4 года назад
Nice explanation
@krishnachaitanya8088
@krishnachaitanya8088 3 года назад
Thanks for the video
@deepalisrivastava3701
@deepalisrivastava3701 2 года назад
Function.prototype.myBind = function(...args) { let context = this; return function(...args2) { context.call(...args, ...args2) } } var res = printDetail.myBind(obj1, "GKP"); res("India", "Passionate"); @Akshay Thank you so much for this amazing content but I do have a doubt if the above is correct or not? It is working fine., then why do I need to use slice and concatenate arrays?
@viveksai9353
@viveksai9353 5 лет назад
You are like the Yoda of bind method. :-D
@shivanshmehrotra9986
@shivanshmehrotra9986 2 года назад
At 4:26 why we stored this in a let variable? Can we use it directly?
@yogeshvitkar1943
@yogeshvitkar1943 3 года назад
Superb
@codingcinemax
@codingcinemax 2 года назад
I am wondering here should be a full organised JavaScript course by you even if paid no issue.
@priyaarya6883
@priyaarya6883 Месяц назад
great!!!
@madmaxfury9773
@madmaxfury9773 8 месяцев назад
@Akshay I have some questions : 1) You told inside JS function, this inside a function is undefined in strict mode. So, how come obj = this points to printName. 2) .call will suppose to call the functions when you type .myBind(name), then how come you are returning that function of its already been called. SOMEONE PLEASE CLARIFY MY DOUBTS?
@shabnamnaaz4676
@shabnamnaaz4676 3 года назад
hey i got promise.all polyfill ques in interview today . i could do it somehow bz of this reference in mind .:).thanks Akshay
@balajisv4052
@balajisv4052 4 года назад
I think that glitch of missing the 2 in args2 was intentional.🤓. Anyway that was a nice video.
@shivanisehdev8817
@shivanisehdev8817 4 года назад
@Akshay Thanks for the amazing explanation. I clearly understood the point that in this video you have created a polyfill for bind() method which is your mybind() method. But where does this point comes that if my browser does not support bind() it should call mybind(). Then I will say I have created a polyfill form my method and successfully set it as a fallback to bind() method for non supporting browsers.
@akshaymarch7
@akshaymarch7 4 года назад
You'll have to override the actual bind method on Function prototype. Actually just go and check the Prototype and Prototypal inheritance video I've created, Shivani. You'll get your answer 😇
@shivanisehdev8817
@shivanisehdev8817 4 года назад
@@akshaymarch7 sure I'll check thanks Akshay
@aashishranamagar8160
@aashishranamagar8160 2 года назад
try this 🔥🔥🔥 Function.prototype.mybind = function () { const [reference, ...args] = arguments return this.apply(reference, args) }
@jaisaram5239
@jaisaram5239 5 лет назад
Please create video on Polyfill for Promise.
@akshaymarch7
@akshaymarch7 5 лет назад
Thanks for your suggestion. I've noted the topic, will try to come up with video covering that soon.
@hadeedtmgggg5837
@hadeedtmgggg5837 Год назад
Thanks sir❣️❣️❣️
@jatinnandwani6678
@jatinnandwani6678 Год назад
Thanks so much
@MrVisheshsingh
@MrVisheshsingh 4 года назад
Wow 😍
@16_piyush2
@16_piyush2 Год назад
Sir please can you explain what is Implicit, explicit and default binding ?
@leela2997
@leela2997 3 года назад
Hi akshay How do we say that this in myBind is printName.Actually "this" always sounds like a tricky concept in Javascript. A video on "this" context will be really helpful for a beginner like me
@anupamboral3918
@anupamboral3918 2 года назад
so it is because ' this' points to the window object ,window object is a global object where the all functions and the variables created with var keyword has been saved . so when you you create a function in global scope js engine saves it into the global object/window object and that's why you can see here 'this' keyword is pointing to the function ,because the function itself saved inside the global object.
@vikramkavide9796
@vikramkavide9796 2 месяца назад
@akshaysaini since we dont have access to es6 features we are writing polyfills for it, and ur using again es6 features inside polufill i didn't get this? can someone explain...!
@mipravin
@mipravin 3 года назад
Hey Akshay, very nice videos. Want to ask is there any browser that does not support bind method? I mean to ask is it necessary now to have polyfill for bind.
@rincyphilip5011
@rincyphilip5011 2 месяца назад
Thank u!
@dodgecu
@dodgecu 5 лет назад
Great, thanks!
@aakanshachoudary3797
@aakanshachoudary3797 3 года назад
Please create the video for Async and await in Javascript.
@SatishSingh-nm3zn
@SatishSingh-nm3zn 2 года назад
@Akshay Can you help me with the below Question? Given a function foo and an object bar, without using call bind and apply and without changing foo, assign bar as a context of foo: function foo() { console.log(this.a); } const bar = { a: "Hello", }
@kondasomu
@kondasomu Год назад
Akshay sir, how we can prevent API multiple times execution
@lsd3284
@lsd3284 3 года назад
The most difficult part that I found was how this refers to printName when mybind is called as a method .
@realsandeep
@realsandeep 3 года назад
@Naman Jain My understanding -> 'this' refers to the object that calls the function . So here mybind function is called by printName (function) (which is Object in JS). Then mybind function will return the call to the printName function
@lucianrusu7033
@lucianrusu7033 4 года назад
thanks for all work, ive learn a lot from your videos. can please let me know if the following is also correct... Function.prototype.myBind = function(...arg){ return (...arg2) => { this.call(...arg, ...arg2) } }
@vishalheble
@vishalheble 4 года назад
I think you cannot call "call" method on "this" inside a function since it is a window obj. Hence it will throw undefined or NaN. @akshay am i right ?
@lucianrusu7033
@lucianrusu7033 4 года назад
@@vishalheble thanks for your reply. However, the solution I found does work.
@vishalheble
@vishalheble 4 года назад
@@lucianrusu7033 oh sorry my bad. That's working coz you are using an arrow function
@lucianrusu7033
@lucianrusu7033 4 года назад
@@vishalheble thank for your reply. Much appreciated
@mishudas8113
@mishudas8113 3 года назад
This video got complicated! Messed up things in second argument.
@rajanlagah4529
@rajanlagah4529 8 месяцев назад
Recently I gave interview at netomi They asked me to create polyfill for bind without using call, apply. I told that i know way with bind or apply but they asked to do it without that I asked chatGPT as well its using apply Any idea how can we do that? I tried updating proto but was not able to make it work
@ayushaggarwal7690
@ayushaggarwal7690 8 месяцев назад
Function.prototype.myBind = function (newContext = {}, ...arg) { if (typeof this !== 'function') { throw new Error(this + "cannot be bound as it's not callable"); } newContext.fn = this; return function (...newArg) { return currentContext.fn(...arg, ...newArg); }; };
@baburamchaudhary159
@baburamchaudhary159 2 года назад
In fact we have bind() method, why we have to implement on our own, any reason?
@mona-m6x
@mona-m6x 3 месяца назад
why do we need polyfills, or binds/ calls/apply. I mean in real world scenarios
@KrishnaKumar-ni4ck
@KrishnaKumar-ni4ck 3 года назад
@akshay Function.prototype.myBind = function(...args){ var obj = this; var params = args.slice(1); return function(...args2){ obj.call(args[0], ...params, ...args2); } } shall we use call like this instead of apply?
@TwoTeaTee
@TwoTeaTee 3 года назад
Just Wow!
@ponmanivenkat
@ponmanivenkat 4 года назад
Hi , is it possible to return those values inside the printname function instead of printing using console.log? if yes ,please tell how, thanks in advance
@vivekreddy8864
@vivekreddy8864 2 года назад
why can't we use "call" instead of "bind" method inside the polyfill Function.prototype.myBind = function (...args1) { let obj = this; return function (...args2) { return obj.call(...args1, ...args2); } }
@ozzyfromspace
@ozzyfromspace 2 года назад
I didn't know we were allowed to use the other methods (call and apply), so my dumb self did it all from scratch 😂 Function.prototype.mybind = function (obj, ...args) { return () => { const newObj = {...obj, fn: this } return newObj.fn(...args); } } You have do something similar for anything other than object reference. call and apply handles this important nuance for you.
@kumarneeraj8614
@kumarneeraj8614 3 года назад
Extremely helpful video @akshay Saini. I have one doubt. Why this below code is not working ? Diff is I used anonymous function Function.prototype.myBind = (...args)=>{ instead Function.prototype.myBind = function (...args){ While logging this obj I am getting {}; can anyone help me to understand it. Function.prototype.myBind = (...args) =>{ // console.log("MyBind Method"); let obj = this; console.log(this); return function(){ // obj.call(args[0]); obj.apply(args[0]); }; } var myName2 = printName.myBind(userDetail); myName2();
@greg1486
@greg1486 Год назад
I get what you are saying, but what I don't understand is why you would do this. What situation would you need something like this? Like... I guess I just don't know what the purpose of the .bind() function is in the first place.
@ricko13
@ricko13 3 года назад
You create a polyfill for bind using _call and apply_ but what if those methods doesn't exist neither
@narendrachowdary6894
@narendrachowdary6894 3 года назад
I am stuck at line 14 , How is let obj = this refers to printName function instead of name object ?
@sagarshekhar6296
@sagarshekhar6296 2 месяца назад
If you want to crystal clear your concepts.....come to Akshay
@priyankverma7434
@priyankverma7434 5 лет назад
Can you tell me the reason how JS is single threaded and async as well?
@akshaymarch7
@akshaymarch7 5 лет назад
Sure, will plan to come up with a video on that topic 😊
@rajeevsharma2404
@rajeevsharma2404 5 лет назад
read about Event loop.
@yuvrajoberoi7834
@yuvrajoberoi7834 4 года назад
Are these things expected from a fresher?
@yogeshchaube2783
@yogeshchaube2783 3 года назад
Function.prototype.myBind = function (context, ...args) { let callee = this; return function(...innerArgs) { callee.call(context, ...args, ...innerArgs); } };
@sunilkumaryadav7705
@sunilkumaryadav7705 4 года назад
fn.call(args[0] , ...params , ...args2 ) will also work the same way as expected. Is there anything which will not be achieved by using the way i am using ? @Akshay
@shivrajnag12
@shivrajnag12 4 года назад
I guess it's same but might differ in some internal implementation for which we might need to do PhD. in JS. Haha
@Nitinkumar-lu7ee
@Nitinkumar-lu7ee Год назад
Hi, what is the meaning of ... (three dots) ebfore args
@bharghavasagarmandadi5360
@bharghavasagarmandadi5360 Год назад
rest parameter u use that whenevr you have no idea how many parameters user might pass so
@lallu12343
@lallu12343 5 лет назад
Function.prototype.bind = function(context, ...args) { return function(...args) { return this.call(context, ...args) }; }
@rajeevsharma2404
@rajeevsharma2404 5 лет назад
Function.prototype.binder = function(){ console.log('arguments', arguments); var context= arguments[0]; var that = this; return function(){ that.apply(context, arguments); } }
@07prasad07
@07prasad07 4 года назад
Hi Akshay, Thank you for your video. I question i would like to ask. Why above code doesnt work if at line 7 i return that string and print at place from where it is called. console.log(printMyName2("India")); this logs as undefined
@07prasad07
@07prasad07 4 года назад
let Person={ fname:"Prasad", lname:"Parab" }; let getDetails=function(){ console.log(this.fname +" "+this.lname); // this works return this.fname +" "+this.lname; } Function.prototype.mybind=function(context){ let obj=this; return function(){ console.log(context); obj.call(context); } } let customBind=getDetails.mybind(Person); console.log(customBind()); // this gives undefined
@kumaraswamy7169
@kumaraswamy7169 4 года назад
return the value inside a function, that will solve your problem let Person = { fname: "Prasad", lname: "Parab" }; let getDetails = function() { return this.fname + " " + this.lname; }; Function.prototype.mybind = function(...args) { let func = this, params = args.slice(0); return function(...args2) { return func.apply(args[0], [...params, ...args2]); }; }; let customBind = getDetails.mybind(Person); console.log("customBind >>>> ", customBind());
Далее
Офицер, я всё объясню
01:00
Просмотров 3,3 млн
call, apply and bind method in JavaScript
10:50
Просмотров 468 тыс.
5 Design Patterns That Are ACTUALLY Used By Developers
9:27
VS Code Is Fighting Back (RIP Cursor?)
16:12
Просмотров 154 тыс.
Learn JSON in 10 Minutes
12:00
Просмотров 3,2 млн