apply 方法 (Function) (JavaScript)

转载:http://msdn.microsoft.com/zh-cn/library/4zc42wh1(v=vs.94).aspx

写在前面:与call方法类似

调用函数,并用指定对象替换函数的 this 值,同时用指定数组替换函数的参数。

apply([thisObj[,argArray]])

参数

thisObj

可选。 要用作 this 对象的对象。

argArray

可选。 要传递到函数的一组参数。

备注

如果 argArray 不是有效对象,则会出现“应为对象”错误。

如果既未提供 argArray 也未提供 thisObj,则原始 this 对象将被用作 thisObj 且不会传递任何参数。

示例

下面的代码演示如何使用 apply 方法。

 1 function callMe(arg1, arg2){
 2   console.log('this value: '+ this);
 3   for (var i in callMe.arguments) {
 4     console.log('arguments: '+ callMe.arguments[i])
 5   }
 6 }
 7 
 8 callMe(1, 2);
 9 // this value: [object Window]
10 // arguments: 1
11 // arguments: 2 
12 
13 callMe.apply('a', ['b', 'c'])
14 // this value: a
15 // arguments: b
16 // arguments: c 

要求

在以下文档模式中受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式、Internet Explorer 8 标准模式、Internet Explorer 9 标准模式、Internet Explorer 10 标准模式和 Internet Explorer 11 标准模式。此外,也在应用商店应用(Windows 8 和 Windows Phone 8.1)中受支持。

原文地址:https://www.cnblogs.com/johnnylion/p/3937456.html