开发者

access to a class variable

I'm trying to access to a class variable through an instance method through an eval (Function)

class Foo
  @classVariable = "helow"

class Bar extends Foo
  bar: -> (new Function("console.log(Foo开发者_Python百科.classVariable)")).call @
  baz: -> console.log(Foo.classVariable)

(new Bar()).baz()
(new Bar()).bar()

but method bar raise an error, telling me ReferenceError: Foo is not defined

Any advices ? Is there another to access a class variable ?


When you create a function by passing a string to the Function constructor, that function can only see the global scope (see the MDN docs). If you wrote

class (window ? global).Foo
  ...

then your code would work. Alternatively, instead of using the Function constructor, just use eval:

bar: -> eval "console.log(Foo.classVariable);"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜