1 apply
Function.apply(obj,args)
复制
apply方法接收两个参数
- obj:这个对象将代替Function类里this对象
- args:这个是数组,它将作为参数传给Function(args-->arguments)
不带第一个参数
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName: "Bill", lastName: "Gates", } person.fullName.apply(person1); // 将返回 "Bill Gates"
复制
带全部参数
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
Function.call(obj[,params...])
复制
call方法接收两个参数
- obj:这个对象将代替Function类里this对象
- args:这个是一个参数列表
不带第一个参数
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"
复制
带全部参数
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
Function.bind(obj[,params...])
复制
bind是ES5 新增的一个方法,它的传参和call类似,也是接收两个参数。
- obj:这个对象将代替Function类里this对象
- args:这个是一个参数列表
不带第一个参数
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"
复制
带全部参数
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不会自动执行目标函数。