从另一个脚本访问javascript变量 [英] access javascript variable from another script

查看:94
本文介绍了从另一个脚本访问javascript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

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

    };
});




  • 我想让'somevar'变量通过插件和I进行修改
    将能够在插件
    调用者函数的作用域中进一步处理已经修改的变量。

  • 我不想使用全局变量。 b $ b
  • 我没有看到将变量作为选项传递给插件,因为它
    将成为插件函数的本地,并且修改不会按照我的理解修改原始变量。 / li>
  • 我可能误解了javascript的工作原理,所以任何
    的答案都是可以理解的。

    • 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.
    • 推荐答案

      当你传递一个基本类型时,它是通过值传递的。但是,如果你传递一个对象,那么它会通过引用传递。所以,你可以做到这一点 -

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

      查看实时演示:: http://jsfiddle.net/rifat/EdRFm/

      这篇关于从另一个脚本访问javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆