一. apply()
方法调用一个具有给定this
值的函数,以及作为一个数组(或类似数组对象)提供的参数。语法:func.apply(thisArg, [argsArray]
thisArg
可选的。在 func
函数运行时使用的 this
值。请注意,this
可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null
或 undefined
时会自动替换为指向全局对象,原始值会被包装。
argsArray
可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func
函数。如果该参数的值为 null
或 undefined
,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。 浏览器兼容性 请参阅本文底部内容。
返回值:
调用有指定this
值和参数的函数的结果。
普通用例:
function add(a, b){
return a + b;
}
function sub(a, b){
return a - b;
}
var a1 = add.apply(sub, [4, 2]); //sub调用add的方法
var a2 = sub.apply(add, [4, 2]);
console.log(a1); //6
console.log(a2); //2
用于继承的示例:
function Per(age, interests) {
this.age = age;
this.interests = interests;
}
function Teacher(age, interests, subject) {
Per.apply(this, [age, interests]);
this.subject = subject;
}
var teacher1 = new Teacher(20, ['eat', 'sleep'], 'English');
console.log(teacher1.English);
二. call()
方法使用一个指定的 this
值和单独给出的一个或多个参数来调用一个函数。
语法:fun.call(thisArg, arg1, arg2, ...)
thisArg
在 fun
函数运行时指定的 this
值。需要注意的是,指定的 this
值并不一定是该函数执行时真正的 this
值,如果这个函数在非严格模式
下运行,则指定为 null
和 undefined
的 this
值会自动指向全局对象(浏览器中就是 window 对象),同时值为原始值(数字,字符串,布尔值)的 this
会指向该原始值的自动包装对象。
arg1, arg2, ...
指定的参数列表。
返回值:使用调用者提供的 this
值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined
。
普通用例:
function add(a, b){
return a + b;
}
function sub(a, b){
return a - b;
}
var a1 = add.call(sub, 4, 2);
var a2 = sub.call(add, 4, 2);
console.log(a1); //6
console.log(a2); //2
用于继承的示例:
function Per(age, interests) {
this.age = age;
this.interests = interests;
}
function Teacher(age, interests, subject) {
Per.call(this, age, interests);
this.subject = subject;
}
var teacher1 = new Teacher(20, ['eat', 'sleep'], 'English');
console.log(teacher1.interests);
注意:该方法的语法和作用与 apply()
方法类似,只有一个区别,就是 call()
方法接受的是一个参数列表,而 apply()
方法接受的是一个包含多个参数的数组。