Home >Web Front-end >JS Tutorial >Examples to explain how to solve this pointing error in JavaScript (picture and text tutorial)

Examples to explain how to solve this pointing error in JavaScript (picture and text tutorial)

亚连
亚连Original
2018-05-21 09:48:231857browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn