apply

apply()函数用于调用当前函数function Object,使用thisObj作为执行时函数内部的this指针引用

functionObject.call( [ thisObj [, arg1 [, arg2 [, args…]]]] )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
name = "张三";
age = 18;

function test(){
    document.writeln(this);
    document.writeln(this.name);
    document.writeln(this.age);   
};

// 全局函数内部的this默认为全局对象window
test(); // [object Window] 张三 18


var obj = {name: "李四", age: 20};
// 更改内部的this指针引用对象为obj
test.apply(obj); // [object Object] 李四 20


function foo(a, b){
    document.writeln(this.name);  
    document.writeln(a);  
    document.writeln(b);  
}
// 改变this引用为obj,同时传递两个参数
foo.apply(obj, [12, true]); // 李四 12 true


function bar(){
    var o = {name: "王五"};
    // 调用foo()函数,并改变其this为对象o,传入当前函数的参数对象arguments作为其参数
    foo.apply(o, arguments);  
}
bar("CodePlayer", "www.365mini.com"); // 王五 CodePlayer www.365mini.com

call

call()函数用于调用当前函数functionObject,使用thisObj作为执行时functionObject函数内部的this指针引用

functionObject.call( [ thisObj [, arg1 [, arg2 [, args…]]]] )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
name = "张三";
age = 18;

function test(){
    document.writeln(this);
    document.writeln(this.name);
    document.writeln(this.age);   
};

// 全局函数内部的this默认为全局对象window
test(); // [object Window] 张三 18


var obj = {name: "李四", age: 20};
// 更改内部的this指针引用对象为obj
test.call(obj); // [object Object] 李四 20


function foo(a, b){
    document.writeln(this.name);  
    document.writeln(a);  
    document.writeln(b);  
}
// 改变this引用为obj,同时传递两个参数
foo.call(obj, 12, true); // 李四 12 true


function bar(a, b){
    var o = {name: "王五"};
    // 调用foo()函数,并改变其this为对象o,传入参数a,b作为其参数
    foo.call(o, a, b);  
}
bar("CodePlayer", "www.365mini.com"); // 王五 CodePlayer www.365mini.com

bind

同上call,apply 用于改变调用函数的this指向

与call,apply区别,bind并不会立即指向函数目标,仅声明this指向

call,apply是立即执行函数,而bind是提取改变this指向的对象,可多次使用

apply、call与bind比较

call,apply是立即执行函数,而bind是提取改变this指向的对象,可多次使用