Coffeescript instance method encapsulation in an Object

心已入冬 提交于 2019-12-12 03:19:59

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/27327408/coffeescript-instance-method-encapsulation-in-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!