前端 2018-06-09 09:50:08

JS中的call()和apply()用法

介绍js中call和apply方法的使用场景

apply()

apply() 方法调用一个函数, 其具有一个指定的this值,以及作为一个数组(或类似数组的对象)提供的参数

语法

fun.apply(thisArg, [arg1, arg2, ...])

参数

  1. this.Arg
    在 func 函数运行时使用的 this 值。
    注意:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的包装对象

  2. argsArray
    数组元素将作为单独的参数传给 func 函数。

返回值

调用有指定this值和参数的函数的结果。

示例

function Person(name, age) {
  this.name = name;
  this.age = age;
  console.log('person') // person
}
function Student(name, age, grade) {
  Person.apply(this, [name, age]);
  this.grade = grade;
}
let student = new Student('alfred', 16, '1-1');
console.log(student.name, student.age, student.grade); // alfred 16 1-1

Student通过apply来实现继承Person类

技巧

找出数组中最大值

// apply骚操作
let arr = [1,10,3,7,5];
let max = Math.max.apply(null , arr);
console.log(max); // 10

max = -Infinity;
// 常规操作
for (let item of arr) {
  if (item > max ){
    max = item;
  }
}
console.log(max); // 10

通过apply内置函数将数组参数转为遍历数组变量

call()

call()方法的作用和 apply() 方法类似,只有一个区别,就是 call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

语法

fun.call(thisArg, arg1, arg2, ...)