2015-11-04 19 views
0

我知道有ES6箭頭函數可以解決這個問題,但這不是問題。我不知道爲什麼這不起作用?我想我聽說某個地方在語言設計上是一個錯誤。我想知道爲什麼這不起作用的基礎機制或一些有用的鏈接。這在對象方法的內部函數中

var test = { 
    firstname: 'David', 
    fn: function() { 

    return ['one', 'two', 'tree'].map(function() { 
     this.firstname; // why is this undefined? 

    }) 
    } 
} 
console.log(test.fn()); 

回答

2

裏面你Array.prototype.map功能引用window對象。爲了解決這個問題,你可以綁定它象下面這樣:

var test = { 
    firstname: 'David', 
    fn: function() { 

    return ['one', 'two', 'tree'].map(function() { 
     console.log(this.firstname); // and now it will be your expected result 

    }.bind(this)) 
    } 
} 

Fiddle,也here是鏈接大約Function.prototype.bind方法

我希望它會幫助你

+0

是,TNX!爲什麼道格拉斯克羅克福德說這是語言設計中的錯誤? – SSS

+0

[這裏](https://nemisj.com/js-without-new-and-this/),部分**作用域替換以及爲什麼沒有「this」用法**圍繞_this_關鍵字做出了很好的解釋 –

相關問題