Access variable created in a method in another way

I'm going crazy over and over on the same topic, with a variable scope. Creating a global variable on this did not work, I tried to return a value in one function in order to use another, but always return an "undefined" error in the console. This is a simple code insert:

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 in which I am trying to access the var myvar value created in method1 (and the variable) inside method2. I found a few things here on the forums, but it seems like I can't get them to work, so any help is more than appreciated.

+4
source share
4 answers

:

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

:

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

.

+3

, . .

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

, , , , . .

+3

:

:

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

, ; :

:

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

.

+2

, , ...

// create shared scope for methods
var methods = (function() {
    // create variable in shared context
    var myvar;
    // define method1
    function method1() {
        // assign value to variable
        myvar = 1;
        // other things going on here in this method
    }
    // define method2
    function method2() {
        // use variable
        console.log(myvar);
    }
    // return methods
    return {
        method1: method1,
        method2: method2
    }
// execute the scope function immediately...
}());

// assign methods to plugin
domElement.plugin({
    method1: methods.method1,
    method2: methods.method2
});

, javascript , , , , , . , , . , .

+1

Source: https://habr.com/ru/post/1628872/


All Articles