【问题标题】:How force use "this" in coffeeScript?如何在咖啡脚本中强制使用“this”?
【发布时间】:2014-07-24 23:59:18
【问题描述】:

我需要像这样在 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”?

谢谢。

编辑:我找到了“burk!”解决方案^^ =>“eval('this')”,但它真的很糟糕。如何做得更好?

【问题讨论】:

  • 您如何调用test 函数,您希望其中的this 是什么?
  • test() 是 MotherClass 类(和 Childclass 也是)的静态方法。看代码^^我希望“this”包含动态调用的类

标签: javascript coffeescript this static-methods


【解决方案1】:

使用细箭头代替粗箭头:

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

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

【讨论】:

  • 哦……太简单了。我认为 => 是在这种情况下保持我的课程所必需的,但不需要^^ 好答案!
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
相关资源
最近更新 更多