The handling of this pointer in JavaScript is a common headache for everyone. Here we give an example to explain the solution to the this pointer error in JavaScript. Friends in need can refer to
to see the following object definition:
1 2 3 4 5 6 7 |
|
This way you can call it normally
1 |
|
The following call will go wrong:
1 2 |
|
1 |
|
Because this pointer has changed, the correct way is as follows:
1 2 |
|
1 |
|
All functions have their special this variable, such as the following forEach
1 2 3 4 5 6 7 8 9 10 11 |
|
Calling sayHiToFriends produces an error:
1 |
|
1 |
|
Solution One: Save this in different variables
1 2 3 4 5 6 7 8 9 10 11 |
|
Solution two:Use the second parameter of forEach, It can assign a value to this
1 2 3 4 5 6 7 8 9 10 |
|
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Seven ways to create objects in JavaScript (summary, must read)
javascript implementation in Java Map object function (detailed answer, code attached)
JavaScript constructor and new operator (key point, must read)
The above is the detailed content of Examples to explain how to solve this pointing error in JavaScript (picture and text tutorial). For more information, please follow other related articles on the PHP Chinese website!