apply 和 call 的用法

apply的用法

语法

func.apply(thisArg, [argsArray])
thisArg
可选的。在func函数运行时使用的this值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
argsArray
可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。如果该参数的值为 null 或 undefined,则表示不需要传入任何参数
返回值:调用有指定this值和参数的函数的结果。


从字面意思理解,apply方法前面是一个函数,它有两个参数,第一个参数是指定this值(没有的时候是全局对象),第二个参数是一个数组或类数组对象,简单的说就是为了改变前面函数this指向

如何用

/* 找出数组中最大/小的数字 */
var numbers = [5, 6, 2, 3, 7];

/* 应用(apply) Math.min/Math.max 内置函数完成 */
var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

/* 代码对比: 用简单循环完成 */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min) 
    min = numbers[i];
}

因为Math.max 不能直接使用数组计算,但是有了apply可以很简单的实现这个问题,这就是它诞生的原因吧

// person对象的fullName方法应用到person1 对象上
var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName: "Bill",
    lastName: "Gates",
}
person.fullName.apply(person1);  // 将返回 "Bill Gates"

参考网址

Function.prototype.apply

tip

Infinity 全局属性,表示无穷大
加上负值后,就是无穷小 -Infinity

call的用法

call的用法基本和apply相似,只是参数不一样,第二个参数不是数组或类数组,而是多个参数

参考网址

Function.prototype.call

bind的用法

bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用。
'function.bind(thisArg[, arg1[, arg2[, ...]]])'

参考网址

Function.prototype.bind

参考

https://github.com/ckinmind/WebHub/issues/3
https://www.cnblogs.com/lengyuehuahun/p/5643625.html
https://www.cnblogs.com/coco1s/p/4833199.html

原文地址:https://www.cnblogs.com/geek12/p/11183618.html