【发布时间】:2011-09-26 23:18:43
【问题描述】:
为了了解 CoffeeScript 实例和类变量的工作原理,我附带了这段代码(结果在 cmets 中)。
class A
x: 1
@y: 2
constructor: (@z) ->
#console.log "const x", x #ReferenceError: x is not defined
console.log "constructor y", @y #undefined
console.log "constructor z", @z # = 3 for A and 6 for B
get: () ->
#console.log "get x", x #ReferenceError: x is not defined
console.log "get y", @y #undefined
console.log "get z", @z # = 3 for A and 6 for B
get2: () =>
#console.log "get2 x", x #ReferenceError: x is not defined
console.log "get2 y", @y #undefined
console.log "get2 z", @z # = 3 for A and 6 for B
@get3: () ->
#console.log "get3 x", x #ReferenceError: x is not defined
console.log "get3 y", @y # = 2
console.log "get3 z", @z #undefined
@get4: () =>
#console.log "get4 x", x #ReferenceError: x is not defined
console.log "get4 y", @y # = 2
console.log "get4 z", @z #undefined
class B extends A
constructor: (@w) ->
super(@w)
console.log '------A------'
i = new A 3
console.log "i.x", i.x # = 1
console.log "i.y", i.y #undefined
console.log "i.z", i.z # = 6
i.get()
i.get2()
A.get3()
A.get4()
console.log '------B------'
i = new B 6
console.log "i.x", i.x # = 1
console.log "i.y", i.y #undefined
console.log "i.z", i.z # = 6
console.log "i.w", i.w # = 6
i.get()
i.get2()
B.get3()
B.get4()
console.log '------------'
这里发生了一些奇怪的事情:
x 变量 我期望从任何方法访问它,但不能从任何方法或构造函数(ReferenceError)访问 x var。我只能从 A 或 B (i.x) 的实例访问它。这是为什么呢?
@y 变量 我期待从任何方法中获取 @y var 值,但它在大多数地方都没有价值(未定义的值,而不是 ReferenceError 异常)。 @y 仅对 @get3 和 @get4 有价值(实例方法?)。如果定义了,为什么我得不到它的值?
@y 和 @z 变量 @y 和 @z 都是实例变量,但是因为 @z 是在构造函数中初始化的,所以它具有不同的行为。 @y 在@get3 和@get4 上有效,@z 在 get 和 get2 上有效。再说一遍,这里发生了什么?
问题是我对这些行为感到非常困惑。这段代码正确吗?那么,我应该多了解CS生成的JS吗?
Tks
【问题讨论】:
标签: coffeescript