Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable created in a method in other method

I am going crazy over and over again on the same topic, variable scope. Creating a global variable on this didn't work, I tried returning the value in one function to use the other one, but always get 'undefined' error back in the console. This is a simplyfied markup of the code:

domElement.plugin({
    method1: function() {
        // create variable
        var myvar = 1;
        // other things going on here in this method
    },
    method2: function() {
        // use variable
        console.log(myvar);
    }
});

This is a jquery plugin where I am trying to access the value of var myvar created in method1 (and is variable) inside of method2. I have found several things here on the forums but can't seem to get any of them working, thus any help is more than appreciated.

like image 962
prettyInPink Avatar asked Jan 06 '23 15:01

prettyInPink


1 Answers

You need to either make the variable scope accessible to both methods:

domElement.plugin({
    myvar: null, 
    method1: function() {
        this.myvar = 1;
    },
    method2: function() {
        console.log(this.myvar); // = null or 1 depending on when you call this function
    }
});

Or you could pass it from one method to the other:

domElement.plugin({
    method1: function() {
        var myvar = 1;
        this.method2(myvar);
    },
    method2: function(v) {
        console.log(v); // = 1
    }
});

I would personally use the first example.

like image 118
Rory McCrossan Avatar answered Jan 19 '23 01:01

Rory McCrossan