看如下對象定義:
'use strict' var jane = { name : ‘Jane', display : function(){ retrun 'Person named ' + this.name; } };
這樣能正常調用
jane.display();
下面的調用會出錯:
var func = jane.display; func()
TypeError: Cannot read property 'name' of undefined
因為,this指向已經改變,正確的方式如下:
var func2 = jane.display.bind(jane); func2()
'Penson named Jane'
所有函數都有其特殊的this變量,如下面的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); }); } }
調用sayHiToFriends會產生一個錯誤:
jane.sayHiToFriends()
TypeError: Cannot read property 'name' of undefined
解決方案一:將this保存在不同的變量中
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); }); } }
解決方案二:利用forEach的第二個參數,它可以給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); } }