访问 CoffeeScript 类中的变量
在下面的代码中,我的印象是使用“粗箭头”将允许我访问类变量。相反,无论箭头是粗箭头还是细箭头,我都无法访问“@accounts”变量。
有什么建议吗?
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', bind_clicks
bind_clicks = (event) ->
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
谢谢。
更新
看起来我之前输入错误导致了一些问题。
下面的代码可以解决这个问题
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', (event) => bind_clicks(event)
bind_clicks: (event) =>
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
,但是,将 bind_clicks 设为公共方法感觉很奇怪。
In the following code, I was under the impression that using a 'fat arrow' would allow me access to the class variables. Instead, regardless of fat or skinny arrow, I am not able to access the '@accounts' variable.
Any suggestions?
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', bind_clicks
bind_clicks = (event) ->
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
Thanks.
Update
Looks like I had mistyped previously causing a bit of my problem.
Here is code that sort-of does the trick
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', (event) => bind_clicks(event)
bind_clicks: (event) =>
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
However, it feels odd to resort to making the bind_clicks a public method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以
在实例方法之前声明bind_clicks。这是私人的。但是,它是一个私有类方法。它会生成一个闭包,这就是原因。我建议使用 _bind_clicks,下划线前缀是定义私有方法的常见约定。因为这在 javascript 中并不存在。
当你声明accounts:[]时也要小心,我建议accounts:null,更多关于这个:http:// html5stars.com/?p=148
You can do that
bind_clicks is declared BEFORE the instance methods. It is private. BUT, it is a private class method. It will generate a closure, that's why. I would suggest to use _bind_clicks, the underscore prefix is a common convention to define private methods. Since this doesn't really exist in javascript.
Be careful also when you declare accounts:[], I would suggest accounts:null, more on this: http://html5stars.com/?p=148
另一种可能的方法是这样做。这和你的很相似。
不要引用我的话,但我不认为 JS 有任何公共/私有方法的概念。我想如果你不想暴露这个方法,你可以这样做。但如果您多次使用此方法,您可能会面临风险或重复操作。
祝你好运!
Sandro
注意:我将事件与主体限制在一起,以便我可以测试代码。
Another possible way of doing this. It's pretty similar to yours.
Don't quote me on this, but I don't think JS has any notion of public/private methods. I supposed if you don't want to expose the method you could do this instead. But you might run the risk or repeating yourself if you use this method more than once.
Good luck!
Sandro
note: I bounded the events from the body so I could test out the code.
您可以将bind_clicks设置为私有,如下所示:
You can make bind_clicks private as follows:
您可以尝试一下: http://jsfiddle.net/zp6LJ/1/
私有方法将必须在构造函数中定义才能实现您正在寻找的内容。
You can try this out: http://jsfiddle.net/zp6LJ/1/
The private method will have to be defined int he constructor function to achieve what you are looking for.