在JavaScript 中,call、apply 和 bind 是 Function 对象自带的三个方法,这三个方法的主要作用是改变函数调用过程中的 this 指向
1 apply
代码语言:javascript复制Function.apply(obj,args)
apply方法接收两个参数
- obj:这个对象将代替Function类里this对象
- args:这个是数组,它将作为参数传给Function(args-->arguments)
不带第一个参数
代码语言:javascript复制var person = {
fullName: function() {
return this.firstName " " this.lastName;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates",
}
person.fullName.apply(person1); // 将返回 "Bill Gates"
带全部参数
代码语言:javascript复制var person = {
fullName: function(city, country) {
return this.firstName " " this.lastName "," city "," country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
2 call
代码语言:javascript复制Function.call(obj[,params...])
call方法接收两个参数
- obj:这个对象将代替Function类里this对象
- args:这个是一个参数列表
不带第一个参数
代码语言:javascript复制var person = {
fullName: function() {
return this.firstName " " this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
person.fullName.call(person1); // 将返回 "Bill Gates"
带全部参数
代码语言:javascript复制var person = {
fullName: function(city, country) {
return this.firstName " " this.lastName "," city "," country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");
3 bind
代码语言:javascript复制Function.bind(obj[,params...])
bind是ES5 新增的一个方法,它的传参和call类似,也是接收两个参数。
- obj:这个对象将代替Function类里this对象
- args:这个是一个参数列表
不带第一个参数
代码语言:javascript复制var person = {
fullName: function() {
return this.firstName " " this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
person.fullName.call(person1)(); // 将返回 "Bill Gates"
带全部参数
代码语言:javascript复制var person = {
fullName: function(city, country) {
return this.firstName " " this.lastName "," city "," country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA")();
可以从上面看出,使用方法基本和call一致,只是后面多了(),其实是bind不会立即执行对应的函数,只是返回对函数的引用。那为什么要引入bind呢,是因为call和apply会自动执行目标函数,从而无法绑定在事件上,因为事件是我们手动触发的,而bind不会自动执行目标函数。