call and apply are when we have a function, and be able to invoke this function (method) on an object as if this object has this method.
In the old days, we wanted to make the arguments of a function into an array, but that object doesn't have the slice() method. So we can invoke slice on that object using call:
It is as if we are using arguments.slice() when arguments does not have that method.
And then call and apply just differ in how they take the arguments, as comma separated or as an array.
In the old days when there was no bind() in JS, we can use call to do a binding, because call lets us choose what the this is when running that method -- the same idea as obj.fn().
yeah, some interviewers ask you to see what experience you have with JS, sometimes when you claim you are familiar with vanilla JavaScript. I think it also helps when you read some docs on MDN and about polyfill, sometimes you also see the usage of call and apply, so it is at least good to know what their working principles are.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
callandapplyare when we have a function, and be able to invoke this function (method) on an object as if this object has this method.In the old days, we wanted to make the arguments of a function into an array, but that object doesn't have the
slice()method. So we can invokesliceon that object usingcall:jsfiddle.net/KennethKinLum/dw7jz6na/
It is as if we are using
arguments.slice()whenargumentsdoes not have that method.And then
callandapplyjust differ in how they take the arguments, as comma separated or as an array.In the old days when there was no
bind()in JS, we can usecallto do a binding, becausecalllets us choose what thethisis when running that method -- the same idea asobj.fn().The operative words here are:
yeah, some interviewers ask you to see what experience you have with JS, sometimes when you claim you are familiar with vanilla JavaScript. I think it also helps when you read some docs on MDN and about polyfill, sometimes you also see the usage of
callandapply, so it is at least good to know what their working principles are.