【Js apply、call、bind 用法】

Js apply、call、bind 用法

apply、call、bind 都是函数的内建方法,为了改变函数运行时上下文而存在的,简单来说就是改变函数的this指向,参考文档 Function apply

apply()

参数:this 值,一个数组或者类数组对象,使用如下:

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

通俗点就是: func.apply(thisObj,Array) ---------- thisObj 对象借了 func 方法对 Array 参数进行处理(参数可有可无)。

call()

参数:this 值,一组参数列表,使用如下:

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

apply 和 call 作用一模一样,就从第二参数有所区别,apply 传入的是一个数组,call 传入的是一个参数列表。

bind()

参数:同call方法,使用如下:

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

与call、apply方法不同的是,bind 方法创建一个新函数返回,并不会立即执行,因此用户可以根据需要自行调整执行时间。

其他应用场景

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())  // 小福贵拥有金手指

总结:

apply、call、bind 都是用来改变函数的this指向;
apply、call、bind 第一个参数都是this要指向的调用对象,也就是想指定的上下文;
apply、call、bind 都可以利用后续参数传参;
bind 是返回对应函数,便于自行调用;apply、call 则是立即调用;

猜你喜欢

转载自blog.csdn.net/weixin_42927679/article/details/125746404