我需要像这样在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。
所以我需要动态的,而不是静态的。
如何在CoffeeScript中强制写“ this”?
谢谢。
编辑:我发现“伯克!”解决方案^^ =>“ eval('this')”,但这确实是令人毛骨悚然的方式。怎么做更好?
最佳答案
使用紧箭头代替粗箭头:
class @MotherClass
@test = ->
Foo.bar(this)
粗箭头使您的函数绑定到
MotherClass
。