在回调函数中理解'this'

Joh*_*hen 3 javascript

我有这个代码

var a = ["a","a"]
a.name = "a"

unique(a)
function unique(arr){
    arr.filter(function(e){
        console.log(this.name) // undefined
    })
}
Run Code Online (Sandbox Code Playgroud)

结果是未定义的,我想知道在这种情况下'this'指的是什么,我该怎么做才能使'this.name'实际上打印一些东西而不是undefined?

sdg*_*uck 5

阅读有关MDN文档Array#filter以了解this未定义的原因:

arr.filter(callback [,thisArg])

如果提供thisArg参数进行过滤,则会在调用时将其传递给回调,以用作此值.否则,将传递未定义的值以用作其此值.最终通过回调可观察到的该值根据用于确定函数所见的通常规则来确定.

您需要通过第二个参数thisArg提供Array#filter上下文来显式设置:

function unique(arr){
    arr.filter(function(e){
        console.log(this.name);
    }, arr);
}
Run Code Online (Sandbox Code Playgroud)