Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access javascript variable from another script

I have the following structure

// script1.js

jQuery(document).ready(function($) {
    var somevar;
    $('somelem').myPlugin();
});


// script2.js

(function($) {
    $.fn.myPlugin = function(options) {

        // access and modify 'somevar' here so that it gets modified
        // in the function which called a plugin

    };
});
  • I want the 'somevar' variable to get modified by plugin and I would be able to work with already modified variable further in the plugin caller function's scope.
  • I do not want to use global variable.
  • I see no use of passing the variable as an option to a plugin as it would become local to a plugin function and modifying would not modify the original variable as I understand.
  • I may misunderstand the concept of how javascript works, so any answer appreciated.
like image 533
noname Avatar asked Aug 02 '26 10:08

noname


1 Answers

When you pass a primitive type, it is passed by value. But, if you pass an object then it'll pass by reference. So, you can do that -

jQuery(document).ready(function($) {
    var somevar = {val: 5};
    $(document).myPlugin(somevar);
    alert(somevar.val);
});


// script2.js

(function($) {
    $.fn.myPlugin = function(options) {
        options.val ++;
        // access and modify 'somevar' here so that it gets modified
        // in the function which called a plugin

    };
})(jQuery);

see the live demo :: http://jsfiddle.net/rifat/EdRFm/

like image 128
Rifat Avatar answered Aug 04 '26 02:08

Rifat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!