Coffeescript实例方法封装在一个Object中 [英] Coffeescript instance method encapsulation in an Object
问题描述
说我有一个Coffeescript类:
class Foo
MyMethodsBar:()=> bar
MyMethodsBaz:()=> baz
有没有办法封装这样的方法(不工作):
class Foo
MyMethods:
bar:()=> bar
baz:()=> baz
所以我可以调用:
f = new Foo()
f.MyMethods.bar()
问题是这个
(或 @
)不是我这样做的实例像一个常规的方法。
感谢,
Erik
不,这是不可能的,除非你创建 MyMethods
在构造函数中,并将 this
绑定到方法。
这是因为当你通过 f.MyMethods.bar()调用一个方法时,
,此
将引用 f.MyMethods
。为了防止这种情况,可以事先将 bar
绑定到特定对象。但是,现在你正在定义 bar
, Foo
的实例到 this
应该引用( f
)还不存在,因此不能在构造函数之外绑定它。
你可以用 f.MyMethods.bar.call(f)
调用这个方法,但是这很麻烦。
Say I have a Coffeescript class:
class Foo
MyMethodsBar: () => "bar"
MyMethodsBaz: () => "baz"
Is there any way to encapsulate methods like this (not working):
class Foo
MyMethods:
bar: () => "bar"
baz: () => "baz"
So I can call:
f = new Foo()
f.MyMethods.bar()
The problem is that this
(or @
) is not the instance when I do this like a regular method.
I'm trying to do this for cleaner mixins/concerns.
Thanks, Erik
Nope, this is not possible, unless you create MyMethods
inside the constructor and bind this
to the methods. At which point you pretty much loose the benefits of using a class.
That's because when you call a method via f.MyMethods.bar()
, this
will refer to f.MyMethods
. To prevent that, you could bind bar
to specific object beforehand. However, at the moment you are defining bar
, the instance of Foo
to which this
should refer to (f
) does not exist yet, so you can't bind it outside of the constructor.
You could call the method with f.MyMethods.bar.call(f)
, but that's rather cumbersome.
这篇关于Coffeescript实例方法封装在一个Object中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!