2015-11-12 47 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)); 

    // ... 
}