2015-11-12 41 views
0
Array.prototype.map.call(arr,this.parse) 

的地圖功能,對於上面的代碼,我做的是我對陣列arr,其中this.parse我使用一些對功能(例如,this.func1)申請this.parse失去這個同時呼籲陣列

儘管如此,我在致電this.func1時丟失了this,它似乎指向全局對象而不是當前類。什麼是保留this的正確方法?

更新 作爲建議通過下面的答案,我用

arr.map(this.parse.bind(this)) 

和它的作品!謝謝!

+0

你是如何定義的'this'的'parse'功能?它如何被添加會影響'this'指向什麼。 – pgreen2

+0

@ pgreen2。這不是函數如何定義的,它是如何被調用的 –

回答

4

您可以將this.parse綁定到當前的this。請記住,this不是詞法範圍,它取決於函數的調用方式。 Function.bind讓你指定什麼this會不管它怎麼叫

Array.prototype.map.call(arr, this.parse.bind(this)); 

另一種選擇是第二個可選參數來分析,它可以讓你指定什麼this會。見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Array.prototype.map.call(arr, this.parse, this); 

另一個選擇是使用不使用詞法範圍this箭頭功能。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Array.prototype.map.call(arr, 
    (current, index, array) => this.parse(current, index, array)); 
2

我只是假設你使用打字稿,因爲你用「打字稿」的帖子。讓我們看看你寫的是什麼:

Array.prototype.map.call(arr,this.parse) 

你爲什麼首先使用call()?有什麼理由嗎?什麼你寫等同於:

arr.map(this.parse) 

從Mozilla的reference on the Array.map()功能:

arr.map(回調[,thisArg])

如果提供了thisArg參數要映射,它將在調用時傳遞給回調函數,以用作其值。否則,未定義的值將被傳遞以用作其值。通過回調最終可以觀察到的這個值是根據通常的規則來確定的,以確定函數所看到的。

我認爲你真正想要做的是捕獲當前對象的這個上下文。如果你只是引用函數的名字,Typescript將不會這樣做,因爲Javascript不會這樣做,而Typescript力求與現有的Javascript向後兼容。

我想你想要做的是這樣的:

private parse(str: string): string { 
    // Just an example -- parse by converting to uppercase 
    return str.toUpperCase(); 
} 

public myMethod(arr: string[]) { 
    // Parse all the elements of arr 
    let parsedArray = arr.map((elem) => this.parse(elem)); 

    // ... 
}