由于我无法使用哈希值,直到他们定义,我才这样做:
@Foo =
Protocol: "http"
Domain: "foo.com"
# Annoying...
@Foo.Url = "#{Foo.Protocol}://#{Foo.Domain}"
理想情况下,我会做这样的事情(一个动作):
# Doesn't work obviously...
@Foo =
Protocol: "http"
Domain: "foo.com"
Url: "#{Foo.Protocol}://#{Foo.Domain}"
有没有办法做到这一点?
我能想出的最佳方法是:
使用闭包
@Foo = do =>
protocol = "http"
domain = "foo.com"
url = "#{protocol}://#{domain}"
protocol: protocol
domain: domain
url: url
使用$ .extend
$.extend @Foo =
protocol: "http"
domain: "foo.com"
,
url: "#{Foo.protocol}://#{Foo.domain}"
谢谢,
埃里克
答案 0 :(得分:1)
一种选择是使用函数而不是属性。
@Foo =
Protocol: -> "http"
Domain: -> "foo.com"
Url: -> "#{this.Protocol()}://#{this.Domain()}"
@Foo.Url() == "http://foo.com"
或者,如果您想使用常规javascript,则可以使用getter
Foo = {
Protocol: 'http',
Domain: 'foo.com',
get Url() {
return this.Protocol + '://' + this.Domain;
}
}
Foo.Url == 'http://foo.com'
Foo.Protocol = 'https'
Foo.Url == 'https://foo.com'