区别:
apply()
方法调用具有给定this
值的函数,并arguments
作为数组(或类数组对象)(参数为数组)
call 和 apply 能够改变函数运行时的上下文(context),改变this的指向
apply语法:
function.apply(thisArg, [argsArray])
thisArg:可选,如果是null
并且undefined
将被全局对象替换,this
调用function函数时,可以指定其他对象。this
指当前对象,即调用对象,改变函数Function内部 this 的指向,继承funtion对象中的方法
argsArray:可选的。一个类数组的对象
返回:使用指定的this
值和参数调用函数的结果
//当thisArg为空,运行上下文为全局对象
var numbers = [5, 6, 2, 3, 7];
var max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
function Person(name,sex) {
this.name = name;
this.sex = sex;
}
function Animal(name,sex,age) {
Person.apply(this,arguments); //this为Animal上下文,this调用Person方法时,apply动态改变Person类里面的this指向,
this.age=age; //Animal对象的this代替Person类里面的this对象,劫持Person对象的属性,方法,继承name,sex属性
}
var people = new Animal("xuesheng","man",10);
console.log(people.name);//xuesheng
console.log(people.sex);//man
console.log(people.age);//10
apply追加数组
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.log(array); // ["a", "b", 0, 1, 2]
apply内置函数 最大值和最小值
// min/max number in an array
var numbers = [5, 6, 2, 3, 7];
// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
console.log(max);//7
var min = Math.min.apply(null, numbers);
console.log(min);//2
call语法
call()
接受参数列表,同时apply()
接受单个参数数组。(参数为列表)
function.call(thisArg, arg1, arg2, ...)
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
// expected output: "cheese"