静态函数中的“this is undefined”

3
class Example{
    static foo():string{
        return this.bar();
    }

    static bar():string{
        return "bar";
    }
}

class Broken{
    static breaksThis(callback: () => string):string{
        return callback();
    }
}

console.log(Example.foo()); // works
console.log(Broken.breaksThis(Example.foo)); // Error at line 3: "this is undefined"

您可以在这里找到互动示例。

我想了解为什么第一个日志按预期工作,但第二个失败了。如何修复它?


1
这个回答解决了你的问题吗?如何在回调函数中访问正确的`this`? - undefined
1
此外还有相关内容:“this”关键字是如何工作的? - undefined
在foo函数中,将return Example.bar();替换为this - undefined
2个回答

3

您在类的静态方法中滥用了this
尝试以下方法以解决问题:

class Example {
    static foo(): string {
        return Example.bar(); /* Here is the fix */
    }

    static bar(): string {
        return "bar";
    }
}

class Broken {
    static breaksThis(callback: () => string): string {
        return callback();
    }
}

console.log(Example.foo()); // works
console.log(Broken.breaksThis(Example.foo));

我喜欢你的解决方法,但它不正确。在TypeScript中,静态函数中的this指的是当前类(遵循继承关系)。 - undefined
@Verim "TypeScript中,静态函数中的this指向当前类(遵循继承关系)" 是错误的。 - undefined
@VLAZ 你有来源吗?所有的集成开发环境和编译器都像我描述的那样工作。 - undefined
2
@Verim,难道你的例子还不足以证明相反的观点吗?这里有另一个例子展示了this仍然在调用时被解析。此外,你可以查看生成的JS代码。在任何时候,this都没有被绑定。另请参阅 - undefined

-1

工作示例

    class Example{
        static foo():string{
            return Example.bar();
        }

        static bar():string{
            return "bar";
        }
    }

    class Broken{
        static breaksThis(ccallback: () => string):string{
           return ccallback();
        }
    }

    console.log(Example.foo()); // works
    console.log(Broken.breaksThis(Example.foo)); 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接