簡體   English   中英

在JavaScript中從另一個函數訪問參數

[英]Accessing parameter of one function from another in javascript

var vehiclePage = (function(){
 // defined these 3 public variable. to share between zoomNoShowFee & submitVehicle 
    this.obj;
    this.rate;
    this.idx;
    var setPara = function(o,t,i){
        this.obj = o;
        this.rate = t;
        this.idx = i;
    }
    return {
        zoomNoShowFee : function(o,t,i){
              // this is existing function. I need to access o,t,i inside submitVehicle function.
            setPara(o,t,i);  // wrote this private function to set values
        },
        submitVehicle : function(){
                   // here I need to access zommNoShowFee's parameter
                     alert(this.rate);
        }
    } // return
})();
vehiclePage.zoomNoShowFee(null,5,3);
vehiclePage.submitVehicle();  // getting undefined

zoomNoShowFee已經存在。 其他開發人員也寫了這個。 我想使用submitVehicle內部傳遞給zoomNoShowFee參數的值。

為此,我在頂部聲明了3個公共變量,並嘗試使用setPara私有函數存儲值。 這樣我就可以訪問SubmitVehicle函數中的那些公共變量。

但是在調用vehhiclePage.submitVehilce()時變得不確定

從根本上說,我做錯了事。 但是不知道在哪里

謝謝你的幫助...

在使用模塊模式時,您要混合一些東西。 this.objthis.ratethis.idx是錯誤的this對象的屬性。 實際上,它們是全局對象的屬性,您可以驗證一下:

vehiclePage.zoomNoShowFee(null,5,3);
alert(rate); // alerts '5'

因此,您必須將值存儲在其他位置。 不過,這很容易:只要使用常規變量而不是屬性,就可以了:

var vehiclePage = (function(){
    var obj, rate, idx;
    var setPara = function(o,t,i){
        obj = o;
        rate = t;
        idx = i;
    }
    return {
        zoomNoShowFee : function(o,t,i){
            setPara(o,t,i);
        },
        submitVehicle : function(){
            alert(rate);
        }
    } // return
})();
vehiclePage.zoomNoShowFee(null,5,3);
vehiclePage.submitVehicle();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM