为什么“ this”在箭头函数中引用全局对象?

时间:2019-09-13 12:54:21

标签: javascript node.js object this

我正在学习javascript:我尝试在函数“ checkAndChange”中访问“ this”,但是根据我声明和导出函数的方式,“ checkAndChange”无法调用以前的函数(this.isErr),因为有时这是指“全局”。

我尝试3种方式,其中1种有效,但我不知道为什么。这是一个例子:

exports.isErr = (err) => {
    return err instanceof Error;
}
// This way works : 
exports.checkAndChange = (obj) => {
    console.log(this); // Here , "this" contains "isErr".
    if (this.isErr(obj))
        return "Error";
    else
        return "It's Okay"
}
function checkAndChange(obj){
    console.log(this); // But not here , "this" refers to "global".
    if (this.isErr(obj)) // TypeError: this.isErr is not a function
        return "Error";
    else
        return "It's Okay"
exports.checkAndChange = checkAndChange; // here i have to bind(this) to make it work and i don't know why.
}

0 个答案:

没有答案