I’ve got a simple question about accessing variables in jQuery. Is there are way to access the variable (wrap) when I call the read function on click of ‘a’.
(function() {
var Example= {
init: function() {
var wrap = 'hello world';
$('a').on('click', this.read);
},
read: function() {
console.log(wrap)
}
};
Example.init();
})();
There are a few ways to accomplish this. Perhaps the easiest is to change the scope of the ‘wrap’ variable. Currently, since it’s declared with a var inside the
initfunction, it’s scoped to theinitfunction and not available outside ofinitdirectly. So, you can declare the ‘wrap’ outside theinit(it could be a property of the ‘Example’ object):This makes ‘wrap’ scoped to ‘Example’ and available as a property of ‘Example’ throughout any function defined within ‘Example’.
(Edit: had to tweak this a bit to properly handle the closure.)