【问题标题】:access object from other scope (javascript) [duplicate]从其他范围访问对象(javascript)[重复]
【发布时间】:2012-12-27 14:47:43
【问题描述】:

可能重复:
Is it possible to gain access to the closure of a function?

请看一下这段代码:http://jsfiddle.net/FH6pB/1/

(function($) {
  var o1 = {
    init: function() { alert('1'); },
  }
  var o2 = {
    init: function() { alert('2'); },
  }
}(jQuery));

(function($) {
  var o3 = {
    init: function() { alert('3'); },
  }
  o2.init();
}(jQuery));


o1.init();
o2.init();

我在 2 个不同的“范围”中有 3 个对象(我不知道在这里使用这个词是否正确,但我想你理解它的意思)。 您可能知道,我无法从外部或其他“范围”访问对象的功能(o.init(); 都不起作用)。

为什么会这样?有办法改吗?

我知道我可以将代码放在一个作用域中,它会很好地工作,但是如果我在单独的 JS 文件中有作用域呢?

提前致谢, 本

【问题讨论】:

  • 小提琴中没有代码。
  • 请不要只把你的代码放在小提琴里,把它也放在问题里。

标签: javascript jquery


【解决方案1】:

不,您不能从外部访问闭包中声明的变量。这就是闭包的工作原理。

一个(通常不好的)解决方案是将变量声明为全局变量:

(function($) {
  window.o2 = {
    init: function() { alert('2'); },
  };
}(jQuery));

o2.init();

但通常,模块模式用于将一些变量设为私有并只返回有用的变量。见this article

【讨论】:

    【解决方案2】:

    你可以使用类似命名空间:

    http://jsfiddle.net/FH6pB/2/

    var scope = {};
    
    (function($) {
      scope.o1 = {
        init: function() { alert('1'); },
      }
      scope.o2 = {
        init: function() { alert('2'); },
      }
    }(jQuery));
    
    (function($) {
      scope.o3 = {
        init: function() { alert('3'); },
      }
      scope.o2.init();
    }(jQuery));
    
    
    scope.o1.init();
    scope.o2.init();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 2018-09-09
      • 2012-10-15
      • 2013-06-05
      相关资源
      最近更新 更多