javascript中的call()和apply()的用法和区别:

今天在网上找了找资料看看觉得挺有用,在此记录下

js函数中都会默认有call和apply方法,这两个方法都是为了改变运行时函数的this指向的。

其实call和apply的用法一样,有区别的地方就是参数不一样。

具体实现的功能举2个小例子:

 1 function add(val1, val2) {
 2     return val1 + val2;
 3 }
 4 
 5 function sub(val1, val2) {
 6     return val1 - val2;
 7 }
 8 
 9 console.log(add.call(sub, 2, 1));//3
10 console.log(add.apply(sub, [2, 1]));//3
View Code
 1 function People(name, age) {
 2     this.name = name;
 3     this.age = age;
 4 }
 5 
 6 function Student(name, age, grade) {
 7     People.call(this, name, age);
 8     // People.apply(this,[name,age])
 9     this.grade = grade;
10 }
11 
12 var student = new Student('小w', 8, '一年级');
13 console.log(student.name + student.age + student.grade);//小w8一年级

从上面的例子可以看出,使用call函数时要指定确定好的参数,当使用apply时可以传入arguments,当做参数

黑科技介绍:apply的特殊用法

由于apply可以使用arguments,发现apply可以做一些其他的用途,例如Math.max或者Math.min这种原生函数做比较时候,是不支持数组的,所以没法将一个数组中最大或者最小的数值取出来的,这个时候我们可以这样:

1 var array = [1, 2, 3];
2 var max = Math.max.apply(null, array);
3 // var max = Math.max.apply(this, array);
4 console.log(max);//3

或者用apply拼接数组:

1 var arr1 = [1, 2, 3];
2 var arr2 = [4, 5, 6];
3 Array.prototype.push.apply(arr1, arr2);
4 // arr1.push.apply(arr1, arr2);
5 // [].push.apply(arr1, arr2);
6 console.log(arr1);//[ 1, 2, 3, 4, 5, 6 ]
原文地址:https://www.cnblogs.com/codingFan/p/14838221.html