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.
call
andapply
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 invokeslice
on that object usingcall
:jsfiddle.net/KennethKinLum/dw7jz6na/
It is as if we are using
arguments.slice()
whenarguments
does not have that method.And then
call
andapply
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 usecall
to do a binding, becausecall
lets us choose what thethis
is 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
call
andapply
, so it is at least good to know what their working principles are.