Example illustration of this pointing to error resolution in JavaScript

  • 2021-06-28 10:26:51
  • OfStack

Look at the following object definitions:


'use strict'
var jane = {
  name  :   ' Jane',
  display : function(){
    retrun 'Person named ' + this.name;
  }
};

This will make the call normal


jane.display();

The following call will fail:


var func = jane.display;
func()

TypeError: Cannot read property 'name' of undefined

Because the this orientation has changed, the correct way is as follows:


var func2 = jane.display.bind(jane);
func2()

'Penson named Jane'

All functions have their own 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 results in an error:


jane.sayHiToFriends()

TypeError: Cannot read property 'name' of undefined

Solution 1: Save this in a different variable


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 2: Using forEach's second parameter, it can assign this a value


jane.display();
0


Related articles: