jney
jney

Reputation: 1912

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.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 ?

Upvotes: 0

Views: 113

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

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);"

Upvotes: 1

Related Questions