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:
'use strict' var jane = { name : ‘Jane', display : function(){ retrun 'Person named ' + this.name; } };
This way you can call it normally
jane.display();
The following call will go wrong:
var func = jane.display; func()
TypeError: Cannot read property 'name' of undefined
Because this pointer has changed, the correct way is as follows:
var func2 = jane.display.bind(jane); func2()
'Penson named Jane'
All functions have their special this variable, such as the following forEach
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; this.friends.forEach(function(friend) { // 'this' is undefined here console.log(this.name + ' says hi to '+ friend); }); } }
Calling sayHiToFriends produces an error:
jane.sayHiToFriends()
TypeError: Cannot read property 'name' of undefined
Solution One: Save this in different variables
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; var that = this; this.friends.forEach(function(friend) { console.log(that.name + ' says hi to '+ friend); }); } }
Solution two:Use the second parameter of forEach, It can assign a value to this
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; this.friends.forEach(function(friend) { console.log(this.name + ' says hi to '+ friend); }, this); } }
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!