[Js apply, call, bind usage]

Js apply, call, bind usage

apply, call, and bind are all built-in methods of the function, which exist to change the runtime context of the function. Simply put, it is to change the this point of the function. Refer to the document Function apply .

apply()

Parameters: this value, an array or array-like object, used as follows:

var arr = [1,2.4,2,0.5,7,3]
console.log(Math.max.apply(Math,arr)) // 7
console.log(Math.min.apply(Math,arr)) // 0.5

The popular point is: func.apply(thisObj,Array) ---------- thisObj object borrows the func method to process the Array parameter (the parameter is optional).

call()

Parameters: this value, a set of parameter lists, used as follows:

var arr = [1,2.4,2,0.5,7,3]
// ... 是 ES6 语法中的扩展运算符。
console.log(Math.max.call(Math,...arr)) // 7
// ...arr同等于将 [1,2.4,2,0.5,7,3] 展开 1,2.4,2,0.5,7,3
console.log(Math.max.call(Math,1,2.4,2,0.5,7,3)) // 7
console.log(Math.min.call(Math,...arr)) // 0.5

The function of apply and call is exactly the same, except that the second parameter is different. apply is passed in an array, and call is passed in a parameter list.

bind()

Parameters: Same as the call method, use as follows:

var arr = [1,2.4,2,0.5,7,3]
// ... 是 ES6 语法中的扩展运算符。
var bindMax = Math.max.bind(Math,...arr)
console.log(bindMax()) // 7
var bindMin = Math.min.bind(Math,...arr)
console.log(bindMin()) // 0.5

Different from the call and apply methods, the bind method creates a new function to return and will not be executed immediately, so users can adjust the execution time according to their needs.

Other application scenarios

var obj = {
    
    
  name: '小福贵'
}
var func = {
    
    
  output: function(){
    
    
    return this.name + '拥有金手指'
  },
  name: '老佛爷'
}
var callFunc = func.output.call(obj) // call、apply 方法
var bindFunc = func.output.bind(obj) // bind 方法创建一个新函数返回,不立即执行
console.log(func.output()) // 老佛爷拥有金手指
console.log(callFunc)  // 小福贵拥有金手指
console.log(bindFunc())  // 小福贵拥有金手指

Summarize:

apply, call, and bind are all used to change the this point of the function;
the first parameter of apply, call, and bind is the call object to be pointed to by this, that is, the context you want to specify;
apply, call, and bind can use subsequent parameters Pass parameters;
bind is to return the corresponding function, which is convenient to call by yourself; apply and call are to call immediately;

Guess you like

Origin blog.csdn.net/weixin_42927679/article/details/125746404