See the following object definition:
'use strict'var jane = { name : 'Jane', display : function(){ retrun 'Person named ' + this.name; }};This will call normally
jane.display();
The following call will cause an error:
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 variables, such as the forEach below
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 saysHiToFriends will produce an error:
jane.sayHiToFriends()
TypeError: Cannot read property 'name' of undefined
Solution 1: 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 2: Use the second parameter of forEach, which can specify 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); }}