We try to represent the Odiv object with this in the callback function, so it feels cool.
|
1 animate (odiv,{"left": 600},2000,function () {
2 This.style.backgroundColor = "Red";
3}); |
But no, this is not odiv in the callback function.
So now we have to think of a way to let callback run, and callback inside this is odiv.
Or:
Execute the callback function, and let the This keyword in the callback function be elem.
Example:
|
1 var obj2 = {
2 "name": "Sloth",
3 "Age": 16,
4 "Sex": "Male"
5}
6
7 function Xianshixinxi () {
8 alert (this.name);
9}
10
11//The meaning of this call statement is two levels:
12//1. The Xianshixinxi function is called
13//2. And this inside of this function is obj.
Xianshixinxi.call (OBJ2);
|
To put it bluntly, the apply and call functions are the same, and the function is to have the function called and to set who this is for the function.
Call is the meaning of English calling, and apply is the meaning of application.
Now tell me the difference:
|
1 var obj = {
2 "name": "Koala",
3 "Age": 18,
4 "Jiehun": false
5}
6
7
8 function Xianshixinxi (a,b,c) {
9 Console.log (this.name);
Ten Console.log (A + B + c);
11}
12
Xianshixinxi.call (obj,2,3,4);
Xianshixinxi.apply (obj,[2,3,4]);
|
Call and apply function, just let a function inside the this set to an object.
For example, this is the Obj object in the Xianshixinxi function. But we found that the Xianshixinxi function has parameters. So now we want to set who this is, and want to pass the parameters to the inside, there is a difference:
|
1 fn.call (obj, parameter 1, parameter 2, parameter 3 ...); |
|
1 fn.apply (obj,[parameter 1, parameter 2, Parameter 3 ...]); |
Call requires you to list all parameters with commas, but apply is to write all the parameters in the array. Even if there is only one parameter, it must be written in the array.
Like what:
|
1 function showinfo (n) {
2 for (var i = 1; I <= n; i++) {
3 Console.log (this.name);
4}
5}
6 Showinfo.call (obj,ten);
7 showinfo.apply (obj,[ten]);
|
Must not be confused, apply to the array, you want to Ah, ly, ly, ly look like List, is an array.
To summarize, these two things are functionally consistent, which is to set the this in a function to an object. The difference is the syntax of the arguments that follow.
On the Apply and call statements of JavaScript