我试图理解CoffeeScript实例和类变量的工作原理,写下了这段代码(结果在注释中)。
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变量 我希望能够从任何方法中访问它,但是无法从任何方法或构造函数中访问x变量(出现ReferenceError错误)。我只能从A或B的实例(i.x)中访问它。为什么会这样?
@y变量 我希望可以从任何方法中获取@y变量的值,但在大多数地方它没有值(undefined值,不是ReferenceError异常)。@y只在@get3和@get4(实例方法?)中有值。如果已定义,为什么我不能获取其值?
@y和@z变量 @y和@z都是实例变量,但由于@z在构造函数中初始化,因此具有不同的行为。@y在@get3和@get4上有效,而@z在get和get2上有效。再次,这里发生了什么?
问题在于我对这些行为感到非常困惑。这段代码是否正确?那么,我应该学习更多关于由CS生成的JS吗?
谢谢