2014-06-21 35 views
1

所以我有一些javascript以下的(僞)結構。如何設置從showUpdates功能父函數的變量this.last_updated,沒有專門引用的名稱分配(my_main_function)。的Javascript範圍和this.Variable

var my_main_function = new main() 

function main() { 
this.last_updated; 

function showUpdates(data){ 
//set this.last_updated= 

// do Stuff 
} 
this.updateMain(){ 
    $.ajax({ 
       url:"/my_url/" 
       type:"POST", 
       datatype:"json", 
       data: {'last_updated':this.last_updated }, 
       success : function(data) { showUpdates(data)}, 
       error : function(xhr,errmsg,err) { 
       alert(xhr.status + ": " + xhr.responseText); }, 
    }); 
} 
} 
+0

甚至_pseudo code_你應該確保它是清潔。是'main'真的周邊'showUpdates'和'updateMain',爲什麼你寫的'VAR this.main_updated',是'this.updateMain'一個函數,my_main_function'的'部分,如果叫意願的'ajax'請求? –

+0

我將更改var名稱以使其更清晰 - 您將看到updateMain調用傳遞給服務器的更新函數上次更新的時間戳。 – user3467349

+0

你對''有什麼意思,但是不需要多個main()'?你只有一個_main_對象,你不會再做一個'new main'?如果是這樣,你根本不需要'new main()'。 –

回答

1

更新的代碼庫一個註釋:

有創建對象的雙向。

如果你需要創建對象的多個時間你會做這樣的:

var YourDefintinon = function() { 
}; 

YourDefintinon.prototype.foo = function() { 

}; 

obj1 = new YourDefintinon(); 
obj2 = new YourDefintinon(); 

obj1.foo(); 

如果你只需要一次在你的代碼你可以那樣做:

var obj = { 

}; 

obj.foo = function() { 

}; 

foo(); 

所以,你將需要main只有一次你的代碼應該是這樣的:
使用Function.prototype.bind(及其polyfill舊版本瀏覽器),以將showUpdates綁定到obj

var main = { 
    last_updated : null 
}; 

function showUpdates(data){ 
    this.last_updated = data.update_time; 
} 

main.updateMain = function() { 
    //<< bind showUpdates to `this` and save the bound function in the local variabel showUpdates 
    var showUpdates = showUpdates.bind(this); 

    $.ajax({ 
    url:"/my_url/" 
    type:"POST", 
    datatype:"json", 
    data: {'last_updated':last_updated }, 
    success : showUpdates, //<< uses the showUpdates variable not the function 
    error : function(xhr,errmsg,err) { 
     alert(xhr.status + ": " + xhr.responseText); 
    }, 
    }); 
}; 

當你不想讓showUpdates訪問別人,你可以整個塊包裝成一個被稱爲立刻功能:

var main = (function() { 
    var main = { 
    last_updated : null 
    }; 

    function showUpdates(data){ 
    this.last_updated = data.update_time; 
    } 

    main.updateMain = function() { 
    var showUpdates = showUpdates.bind(this); 

    $.ajax({ 
     url:"/my_url/" 
     type:"POST", 
     datatype:"json", 
     data: {'last_updated':last_updated }, 
     success : showUpdates, 
     error : function(xhr,errmsg,err) { 
     alert(xhr.status + ": " + xhr.responseText); 
     }, 
    }); 
    }; 

    return main; 
}());