试图了解CoffeeScript实例和类变量是如何工作的,我使用了这段代码(结果在注释中)。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 VAR 我期待从任何方法,但X访问var它不能从任何方法或构造访问(的ReferenceError) 。我只能从A或B(i.x)的实例访问它。这是为什么?我期待从任何方法获得@y var值,但它在大多数地方没有值(未定义的值,不是ReferenceError异常)。 @y仅在@ get3和@ get4(实例方法?)上具有值。如果定义了,为什么我不能得到它的价值?
@y和@z var @y和@z都是实例变量,但是因为@z在构造函数中被初始化,所以它具有不同的行为。 @y在@ get3和@ get4上有效,@z在get和get2上有效。再次,这里发生了什么?
事情是,我真的很困惑这些行为。这段代码是否正确?那么,我是否应该更多地了解由CS生成的JS?
韩国社交协会
太棒了!我认为最重要的是:“作为一个基本指南,尽量不要在功能体外使用@,一切都会变得更有意义”真实! –