Foo.bar(this) # same with @ 但是如-6ren">
gpt4 book ai didi

javascript - 如何在coffeeScript中强制使用 "this"?

转载 作者:行者123 更新时间:2023-11-28 01:07:01 24 4
gpt4 key购买 nike

我需要在 MotherClass 中定义一个静态方法,如下所示:

class @MotherClass
@test = =>
Foo.bar(this) # same with @

但是如果你尝试一下:http://coffeescript.org/#usage ,你会看到,这是在“MotherClass”中自动编译的。

所以,它是一样的,但不是真的!

事实上,我有一个 ChildClass 继承于 MotherClass

  @ChildClass extends @MotherClass

因此 ChildClass.test() 被定义。但就像这样:

function() {
return Foo.bar(MotherClass);
};

我需要 Foo.bar 的第一个参数是 ChildClass 中的 ChildClass(如果我创建 ChildClass2 类,则为 ChildClass2...),而不是 MotherClass。所以我需要动态的 this,而不是静态的。

如何在 CoffeeScript 中强制写入“this”?

谢谢。

编辑:我找到了“burk!”解决方案^^ =>“eval('this')”,但这确实是蹩脚的方式。如何做得更好?

最佳答案

使用细箭头而不是粗箭头:

class @MotherClass
@test = ->
Foo.bar(this)

粗箭头使您的函数绑定(bind)到MotherClass

关于javascript - 如何在coffeeScript中强制使用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com