class @A
A_Function_Alias: => @my_function
my_function: =>
usage_of_alias: =>
@A_Function_Alias.call()
我想要的是usage_of_alias
usage_of_alias: => @A_Function_Alias
并使其表现相同。即我想要一个更实用的样式语法。我尝试了多种组合但没有成功。事实上,我必须评估我的功能才能获得里面的好东西,这让我很困扰。
一个应用程序可以代替这个:
event: => new Event(@my_function)
通过 event.call().hi()
我可以有一些其他声明,允许我以 event.hi()
行为更像字段而不是属性。
最佳答案
我想你想要这个:
class @A
my_function: => alert 'my function!'
A_Function_Alias: @::my_function
usage_of_alias: =>
@A_Function_Alias()
# some other code...
See what this compiles to here.
评估类时,@
是类构造函数对象,即类对象本身。 ::
运算符可让您深入了解原型(prototype)。因此,类主体中的 @::foo
编译为 MyClass.prototype.foo
。
因此,它首先创建一个名为 my_function
的普通实例方法,在 A.prototype.my_function
上定义。然后我们创建一个名为 A_Function_Alias 的新实例方法,并直接从我们刚刚创建的类对象原型(prototype)中分配该函数。现在,my_function
和 A_Function_Alias
都指向完全相同的函数对象。
但是作为一个更明智的选择,我是否可以建议一种模式,定义类可以使用的私有(private)内部函数,然后更直接地分配它,而不需要疯狂地访问原型(prototype)?
class @A
# Only code inside this class has access to this local function
innerFunc = -> alert 'my function!'
# Assign the inner funciton to any instance methods we want.
my_function: innerFunc
A_Function_Alias: innerFunc
usage_of_alias: =>
@A_Function_Alias()
# or
@my_function()
# or
innerFunc()
# they all do the same thing
关于coffeescript - CoffeeScript 中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472137/