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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With