How does 'call' work in javascript?

后端 未结 2 1561
不知归路
不知归路 2020-12-03 15:48

I have a question on \'call\' in javascript.

var humanWithHand = function(){
    this.raiseHand = function(){
        alert(\"raise hand\");
    }
}

var hum         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 16:11

    .call() sets the this value and then calls the function with the arguments you passed to .call(). You use .call() instead of just calling the function directly when you want to set the this value inside the called function rather than let it be set to whatever javascript would normally set it to.

    .apply() is a sister function. It can also set the this value and it can take arguments in an array so it can be used when you are trying to pass a variable argument list from some other function call or when you're constructing an argument list programmatically which may have different numbers of arguments depending upon the situation.

提交回复
热议问题