定义
-
call方法:
语法:function.call(thisArg, arg1, arg2, ...)
定义:call()调用一个function,而这个function的this替换为给定的thisArg对象,并且函数参数可以一个一个的单独提供(The call() method calls a function with a given this value and arguments provided individually.
)。
说明:call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisArg指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 -
apply方法:
语法:function.apply(thisArg, [argsArray])
定义:apply()调用一个function,而这个function的this替换为给定的thisArg对象, 并且函数参数必须是数组形式。(The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object)
.)。
说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisArg 任何一个参数,那么 Global 对象将被用作 thisArg, 并且无法被传递任何参数
apply和call区别:
apply()和call()方法的作用一样,都是在特定的作用域中调用函数, 。区别在于接受参数的方式不同。
call和apply可以改变函数作用域,将this指针指向改方法的第一个参数。
好处
这两个方法可以扩充作用域,使得对象不需要与方法之间有任何耦合关系了。
扩展
:其实还有bind()方法,用来创建一个函数的实例,其this值会被绑定到给定bind()函数的值。比如:
一句话总结:
A全call单:apply的参数是数组,而call是单个单个的。他们都是在特定的作用域中调用函数。
Bind是返回绑定特定作用域的一个新的函数。
var o = {color: 'blue'};
function sayColor() {alert(this.color)};
var objColor = sayColor.bind(o);
objColor(); // blue
例子
例1: 可用通过打印的this看出,不同的调用,this指向的对象是不一样的。
其中指定null或者正常调用函数,this指向的是全局变量window,而当传入thisArg时,this就指向的是thisArg。从而实现了改变this为你想要的对象。
function fun1(x, y) {
console.log(x + y);
console.log('this = ', this);
}
function fun2(x, y) {
var myName = 'jason';
console.log(x - y);
}
fun1(3,2)
// 5 <--- result
// this = Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
fun1.call(null, 3,2)
// 5 <--- result
// this = Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
fun1.call(fun2, 3, 2)
// 5 <--- result
// this = ƒ fun2(x, y) {
// var myName = 'jason';
// console.log(x - y);
//}
例2:
window.color = 'red';
var o = {color: 'blue'};
function sayColor() {
alert(this.color);
}
sayColor(); // red
sayColor.call(this); // red
sayColor.call(window); // red
sayColor.call(o); // blue
例三: 合并数组
如果你需要合并两个数组,你可以使用Array.concat()函数:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6]; //不适用大数组
**但是,这个函数对于大数组来说不并合适,因为它将会创建一个新的数组并消耗大量的内存。**在这种情况下,你可以使用Array.push.apply(arr1,arr2),它不会创建一个新数组,而是将第二个数组合并到第一个数组中,以减少内存使用:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];