The usage of call(), apply(), and bind() in JavaScript
Category Programming Techniques
It's actually a very simple concept; with ten minutes of careful study, you can go from being completely confused to fully understanding!
First, understand the following:
Example 1
obj.objAge; // 17
obj.myFun() // Xiao Zhang's age undefined
Example 2
shows() // Blind monk
Compare the difference in this between the two; in the first example, the this inside the print points to obj, and in the second example, the this of the globally declared shows() function is window;
1. call(), apply(), and bind() are all used to redefine the this object!
For example:
obj.myFun.call(db); // Dema's age 99
obj.myFun.apply(db); // Dema's age 99
obj.myFun.bind(db)(); // Dema's age 99
Apart from the extra () at the end of the bind method, the results are consistent!
From this, we can conclude that bind returns a new function, which you must call to execute.
2. Compare the parameter passing of call, bind, and apply
obj.myFun.call(db, 'Chengdu', 'Shanghai'); // Dema's age 99 from Chengdu to Shanghai
obj.myFun.apply(db, ['Chengdu', 'Shanghai']); // Dema's age 99 from Chengdu to Shanghai
obj.myFun.bind(db, 'Chengdu', 'Shanghai')(); // Dema's age 99 from Chengdu to Shanghai
obj.myFun.bind(db, ['Chengdu', 'Shanghai'])(); // Dema's age 99 from Chengdu, Shanghai to undefined
Subtle differences!
From the above four results, it is not difficult to see:
The first argument of call, bind, and apply is the object to which this points, and the second argument differs as follows:
The parameters for call are directly inserted, with the second, third, and nth parameters separated by commas and placed directly after obj.myFun.call(db, 'Chengdu', ..., 'string').
All parameters for apply must be placed in an array and passed in obj.myFun.apply(db, ['Chengdu', ..., 'string']).
Bind, in addition to returning a function, has parameters like call.
Of course, the parameters of the three are not limited to the string type, allowing various types, including functions, objects, etc.!
>
Original article link: https://www.cnblogs.com/Shd-Study/p/6560808.html
** Click here to share notes
-
-
-