【发布时间】:2018-12-24 12:50:30
【问题描述】:
我正在使用打字稿。我在类的方法中使用方法Array.some。
像这样:
class Example {
constructor(private readonly foo: string) {}
test(array: Array<string>) {
array.some(function (element) {
if (element == this.foo) {
return true
} else {
return false
}
})
}
}
但是,我无法访问array.some 内部的this.foo。我只能在array.some之外访问它。
我阅读了文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
似乎我必须为可选参数thisArg 传递一个值。但我不确定我应该把它放在我的代码中的什么地方。
我试过了,但是没用。
class Example {
constructor(private readonly foo: string) {}
test(array: Array<string>) {
array.some(function(element) {
if (element == this.foo) {
return true
} else {
return false
}
}, this : Example)
}
}
【问题讨论】:
-
您可以在
Array.some方法中将this用作第二个参数(所以在回调之后)。对于您的示例,array.some(function(element) { ... }, this)将起作用。但是还有很多其他方法可以避免这个问题,请参阅this question。 -
我试过那个方法,但是我有很多错误,我会把它们放在我的父帖子中。
-
是的,我明白了。这里有些混乱,因为您不需要向
this添加类型注释(也不能按照您显示的方式)。您只需将其作为参数传递给some方法,就像其他任何参数一样,因此删除: Example部分,使其读取为.some(function(element) { ... }, this)。 -
当我删除类型注释时,我收到以下关于
this.foo的错误。 "this 隐含类型为 any,因为它没有类型注释" -
啊,那样的话你可能确实需要给它一个类型。在这种情况下,正确的语法是
.some(function(element) { ... }, this as Example)。: <type>语法只能在声明变量、函数参数或类字段时使用。as关键字在 typescript 中用于进行类型断言,这就是你需要的。
标签: javascript arrays typescript