2011-08-17 191 views
0

我試圖通過一個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() 

但方法bar產生一個錯誤,告訴我ReferenceError: Foo is not defined

任何意見? 是否有另一個訪問類變量?

+1

「acceed」是什麼意思? – Paul

+0

@保爾可能「訪問」是一個好詞。英語不是我的母語 – jney

+0

不用擔心,謝謝你的澄清。我爲你編輯了這個問題。 – Paul

回答

1

當您通過將字符串傳遞給構造函數Function來創建函數時,該函數只能看到全局作用域(請參閱the MDN docs)。如果你寫了

class (window ? global).Foo 
    ... 

然後你的代碼將工作。或者,不使用Function構造函數,只需使用eval

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

謝謝,我會嘗試你的解決方案,當我回到我的家。我已經嘗試過使用'eval' – jney