我正在学习CoffeeScript,我有一个轻微的头痛,我还没有完全弄清楚。如果我创建一个对象来执行某些事情,我偶尔需要一个实例变量,以便在方法之间共享该对象。例如,我想这样做:
testObject =
var message # <- Doesn't work in CoffeeScript.
methodOne: ->
message = "Foo!"
methodTwo: ->
alert message但是,不能在var中使用CoffeeScript,如果没有声明,message只能在methodOne中可见。那么,如何在CoffeeScript中的对象中创建实例变量呢?
更新:在我的示例中修复了错误,所以这些方法实际上是方法:)
发布于 2012-04-12 21:31:49
你不能喜欢这样。引用语言参考
因为您没有直接访问var关键字的权限,所以不可能故意隐藏外部变量,因此只能引用它。因此,如果您正在编写深度嵌套的函数,请小心,不要意外地重用外部变量的名称。
然而,在JS中,您试图做的事情也是不可能的,这相当于
testObject = {
var message;
methodOne: message = "Foo!",
methodTwo: alert(message)
}这是无效的JS,因为您不能在这样的对象中声明变量;您需要使用函数来定义方法。例如,在CoffeeScript中:
testObject =
message: ''
methodOne: ->
this.message = "Foo!"
methodTwo: ->
alert message您还可以使用@作为“this.”的快捷方式,即@message而不是this.message。
或者考虑使用CoffeeScript的类语法
class testObject
constructor: ->
@message = ''
methodOne: ->
@message = "Foo!"
methodTwo: ->
alert @message发布于 2012-04-13 00:09:57
为了补充@Lauren的答案,你想要的基本上是模块模式
testObject = do ->
message = null
methodOne = ->
message = "Foo!"
methodTwo = ->
alert message
return {
methodOne
methodTwo
}其中,message是一个“私有”变量,仅适用于这些方法。
根据上下文,还可以在对象之前声明消息,以便这两个方法都可用(如果在此上下文中执行):
message = null
testObject =
methodOne: -> message = "Foo!"
methodTwo: -> alert message发布于 2012-04-12 21:32:44
使用@指向this
testObject =
methodOne: ->
@message = "Foo!"
methodTwo: ->
alert @messagecoffeescript.org上的固定版本
https://stackoverflow.com/questions/10132035
复制相似问题