2011-11-07 103 views
3

我正在嘗試爲Web應用程序編寫一些JavaScript函數。如何在javascript中訪問parent函數的公共屬性?

繼從這裏的建議:How do I declare a namespace in JavaScript?

我試圖使代碼不顯眼通過命名功能包的一切,但我遇到的困難是在父函數訪問屬性小孩匿名函數內部時。

例如:

var title_picker = new function(){ 
    // This property should be public 
    this.callback=function(){}; 


    var ok=function(){ 
     var title = $('input#title').val(); 
     callback(title) // <--- 
    } 
... 

當「OK」功能裏面,什麼是引用「回調」屬性的最佳方式?

回答

4

隨着代碼寫的,沒有沒有。

您可以訪問父級範圍內的變量,除非它們被覆蓋在較窄的範圍內。

this總是被覆蓋。

可以複製this到,雖然範圍仍然另一個變量:

var title_picker = new function(){ 

    var self = this; // Copy this to a variable that stays in scope 

    // This property should be public 
    this.callback = function(){}; 


    var ok=function(){ 
     var title = $('input#title').val(); 
     self.callback(title) // self is still in scope 
    } 
... 
+0

謝謝,這看起來像它會做的伎倆很好。出於興趣,爲什麼厭惡新關鍵字。我的理解對新關鍵字的一般含義非常模糊。在這種情況下,它似乎運行該函數並返回其「this」範圍,這正是我想要的情況。 (爲了能夠例如從我的代碼中的其他地方觸發title_picker.show())。 – Chris

+0

@Chris - 您正在使用函數表達式。當你調用你之前定義的函數時,你會使用'new',你將像使用類一樣使用...和argh。不,我認爲你需要這個「這個」。我從來沒有見過任何人使用這樣的函數*表達式*。 – Quentin

2

也許是這樣的:

var title_picker = new function(){ 
    // This property should be public 
    this.callback=function(){}; 
    var that = this; 


    var ok=function(){ 
     var title = $('input#title').val(); 
     that.callback(title) // <--- 
    } 
... 

雖然現在有很多框架,爲你做這種事情(YUI,道場,原型...)

相關問題