has been to call and apply very vague, today finally understand, share out to everyone.
Apply Call bind method
var ZS = {
Name: "Zhang San",
Sex: "Male",
Age: "25 years old",
Say:function () {
Console.log (this.name+ "," +this.sex+ ", this year" +this.age ")
}
}
var LS = {
Name: "John Doe",
Sex: "Female",
Age: "28 years old"
}
Zs.say (); Zhang San, male, 25 years old this year.
Zhang San has a say method that can console my personal information.
How to display John Doe's personal information with Zhang San's say method?
ZS.say.apply (LS); John Doe, female, 28 year old
ZS.say.call (LS); John Doe, female, 28 year old
ZS.say.bind (LS) (); John Doe, female, 28 year old
! Note Zhang San did not give say to John Doe, John Doe There is no say method.
If the direct write Xw.say.bind (XH) will not have any results, see the difference?
Both call and apply are direct calls to the function, and the Bind method returns a function, so it needs () to be called later.
the difference between call and apply
var WW = {
Name: "Harry",
Sex: "Male",
Age: "30 years old",
Say:function (company,position) {
Console.log (this.name+ "," +this.sex+ ", this year" +this.age+ ", currently employed in" +company+ ", the position is:" +position);
}
}
var ZL = {
Name: "Zhao Liu",
Sex: "Female",
Age: "33 years old"
}
Ww.say ("Ali", "web front-end engineer"); Harry, male, 30 years old, currently working for Ali, Position: Web front-end engineer
By call and apply, Zhao Liu can also use this say method to
WW.say.call (ZL, "Baidu", "canvas Engineer"); Zhao Liu, female, 33 years old, is currently employed in Baidu, the position is: Canvas engineer (call after the parameters and say method is one by one corresponding);
WW.say.call (ZL, "Baidu", ["Baidu", "canvas Engineer"]); Zhao Liu, female, 33 years old, is currently employed in Baidu, the position is: Canvas Engineer (the second parameter of apply is an array, the elements in the array are corresponding to the say method one by one)
The difference between call and apply in JavaScript