Accessing a 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 parameter
                     alert(this.rate);
        }
    } // return
})();
vehiclePage.zoomNoShowFee(null,5,3);
vehiclePage.submitVehicle();  // getting undefined

      

zoomNoShowFee already exists. Several other developers have written this. I want to use the values ​​passed to zoomNoShowFee parameters inside submitVehicle.

To do this, I declared 3 public variables at the top and tried to store the values ​​using the private setPara function. so i can access these public variables in submitVehicle function.

But getting undefined when vehhiclePage.submitVehilce () is called

Basically, I am doing something wrong. But I don't know where ...

Thanks for any help ...

+2


a source to share


1 answer


When using a module template, you are mixing a few things. this.obj

, this.rate

and this.idx

are properties of the wrong object this

. In fact, they are properties of the global object, and you can check this:

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

      



So, you have to store your values ​​somewhere else. It's pretty straightforward: use regular variables instead of properties and you're good to go:

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

      

+1


a source







All Articles