语法
func.apply(thisArg, [argsArray])
参数 apply()的参数第一个参数是改变的this指向的,第二个参数是实参列表,可以是数组,如果是数组,传输过去的时候可以自动展开,就跟ES6中解构一样
参数详解
thisArg在func函数运行时指定的this值。在这里需注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null或者undefined时,会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。argsArray是一个数组或者类数组的对象,其中的数组元素将作为单独的参数传给func函数。如果该参数的值为null或者undefined,则表示不需要传入任何的参数。
返回值
用指定的this值和参数调用函数的结果。
apply()和call()的区别
apply()和call()非常相似,不同之处在于提供参数的方式。
apply()使用参数数组。如 func.apply(this, ['eat', 'bananas']),或数组对象, 如 fun.apply(this, new Array('eat', 'bananas'))
call()使用分别提供的参数(参数的列表)。如 func.call(this, arg1, arg2, ...)
示例
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.apply(this, [name, price]);
this.category = 'food';
}
function Toy(name, price) {
Product.apply(this, [name, price]);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);