On call and apply methods in JS

clipboard.png

questions you want to answer:

  • Why can"t the call method be called through apply ?
  • Why is the second and third output -Infinity ?
  • Why does the Reflect object provide only the apply method and not the call method?

I don"t know if my understanding is wrong. In short, this question has been bothering me for a long time. I hope a great god can help me solve it.

May.09,2022
The usage of

is wrong in itself. The first parameter of call and apply is the this passed to it when the target function is called. You use this to pass the function to this to call or apply , so it's wrong, but just happens to support this calling method in the first way.


you need to figure out the function and difference between call () and apply () , both of which change the direction of the this object. For example:

var obj = {
   name:"abcd"
}
function fn1(){
    console.log(this.name);//undefined
}
function fn2(){
   fn1.call(obj,null);
   console.log(this.name);//abcd
}

replacing call with apply has the same result. The difference between the two is that the passed parameter, the first parameter is the object to be changed, the second parameter is different, call passes an array item parameter, apply passes an array parameter, or it can be the function's arguments object. For example,

var obj2 = {
    name:'abcd',
    sex:'xx'
}

function fn1(name,sex){
  return name + sex;
}
function fn2(){
   return fn1.apply(obj2,['hhh','male']);//hhhmale
}

both methods are non-inherited.


thanks for inviting ~ you can read these two articles, and then look back at your own questions, which should answer your questions.
JS Magic Hall: get to know Function.prototype.call
interviewer asked: can you simulate the call and apply methods of JS

Menu