在JavaScript 中,call、apply 和 bind 是 Function 對象自帶的三個方法,這三個方法的主要做用是改變函數調用過程當中的 this 指向數組
1 applyapp
Function.apply(obj,args)
apply方法接收兩個參數ide
obj:這個對象將代替Function類裏this對象函數
不帶第一個參數this
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName: "Bill", lastName: "Gates", } person.fullName.apply(person1); // 將返回 "Bill Gates"
帶所有參數code
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對象ip
不帶第一個參數ci
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對象
不帶第一個參數
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不會自動執行目標函數。