Using Variables in JQuery Functions

I have a simple question about accessing variables in jQuery. Is there a way to access the variable (wrap) when I call the read function when I click "a".

(function() {
    var Example= {
        init: function() {
            var wrap = 'hello world';
            $('a').on('click', this.read);
        },

        read: function() {
            console.log(wrap)
        }
    };

    Example.init();
})();
+3
source share
6 answers

There are several ways to do this. Perhaps the easiest way is to change the scope of the wrap variable. Currently, since it is declared using var inside a function init, it is bound to a function initand is not initdirectly accessible outside . Thus, you can declare "wrap" outside init(this may be a property of the "Example" object):

    var Example= {
        wrap: 'hello world',
        init: function() {
            var self = this;
            $('a').click(function(){
                self.read();
            });
        },

        read: function() {
            console.log(this.wrap);
        }
    };

    ​Exa​mple.init();

'wrap' 'Example' 'Example' , 'Example'.

(Edit: .)

+3
(function() {
    var wrap;
    var Example= {
        init: function() {
            wrap = 'hello world';
            $('a').on('click', this.read);
    ...

, .

+3
(function() {
    var Example= {
        init: function() {
            this.wrap = 'hello world';
            $('a').on('click', this.read);
        },
        read: function() {
            console.log(this.wrap)
        }
    };
    Example.init();
})();
0
source

try the following: (Fiddle: http://jsfiddle.net/jRJFQ/3/ )

(function(){
    var Example= {
        wrap:null,
         init: function() {
            this.wrap = 'hello world';
            $('a').on('click', this.read);
         },

        read: function() {
            console.log(Example.wrap)
        }
    };
    Example.init();
}​)();​
0
source

If you are considering using the expander module template, you can determine which variables are private and which are publicly available:

var Example = (function(){

    var wrap = 'hello world',
        init = function(){
            ...
        },
        read = function(){
            ... // You can use `wrap` here
        };

    return { // Return public variables and methods
        init: init,
        read: read
    };

})();

Example.init();
0
source

yup, this should do this:

(function() {
    var wrap;
    var Example= {
        init: function() {
            var wrap = 'hello world';
            $('a').on('click', this.read);
        },

        read: function() {
            console.log(wrap)
        }
    };

    Example.init();
})();
-1
source

All Articles