开发者

access to a class variable

开发者 https://www.devze.com 2023-03-29 07:46 出处:网络
I\'m trying to access to a class variable through an instance method through an eval (Function) class Foo

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

精彩评论

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