2010-05-31 107 views
2

好吧,我看到一些Java给出的参考,但没有JavaScript(希望你知道是完全不同的)。所以这是代码特定的:Javascript参考外部对象来自内部对象

function Sandbox() { 
    var args = Array.prototype.slice.call(arguments) 
     , callback = args.pop() 
     , modules = (args[0] && typeof args[0] === 'string' ? args : args[0]) 
     , i; 

    if (!(this instanceof Sandbox)) { 
     return new Sandbox(modules, callback); 
    } 

    if (!modules || modules[0] === '*') { 
     modules = []; 
     for (i in Sandbox.modules) { 
      if (Sandbox.modules.hasOwnProperty(i)) { 
       modules.push(i); 
      } 
     } 
    } 

    for (i = 0; i < modules.length; i++) { 
     Sandbox.modules[modules[i]](this); 
    } 

    this.core = { 
     'exp': { 
      'classParser': function (name) { 
       return (new RegExp("(^|)" + name + "(|$)")); 
      }, 
      'getParser': /^(#|\.)?([\w\-]+)$/ 
     }, 
     'typeOf': typeOf, 
     'hasOwnProperty': function (obj, prop) { 
      return obj.hasOwnProperty(prop); 
     }, 
     'forEach': function (arr, fn, scope) { 
      scope = scope || config.win; 
      for (var i = 0, j = arr.length; i < j; i++) { 
       fn.call(scope, arr[i], i, arr); 
      } 
     } 
    }; 

    this.config = { 
     'win' : win, 
     'doc' : doc 
    }; 

    callback(this); 
} 

如何从this.core.forEach中访问this.config.win?或者这是不可能的?

在沙盒()函数的主体

回答

5

,像这样:

var self = this; 

,然后;

self.config.win 
核心部分

当上下文敏感的“本”改变

+1

挑剔,但这不是闭包。 – nickf 2010-05-31 01:01:20

+0

非常感谢,除了沙盒功能之外,我尝试过在任何地方(工作中的漫长一天可能没有帮助)。 – Akidi 2010-05-31 01:16:59

+0

我见过'那个'用了很多。 'var that = this;'。 – gradbot 2010-05-31 01:56:32

1

你也可以使用函数表达式但是这需要您this.core之前定义this.config。这可以防止您必须使用局部变量。但是,请注意,这会捕获该值而不是引用它,因此如果您为config分配了一个新值,它将不会对forEach产生影响。由于该对象未被克隆,因此您仍然可以更改config.win。如果使用不当,这种行为可能会很微妙,并会导致错误。

尽管如此,最好使用Jonathan建议的var self = this;。然而,这是做到这一点的另一种方式,并且在有用的情况下也是如此。

this.config = { 
    'win' : "win", 
    'doc' : "doc" 
}; 

this.core = { 
    'exp': { 
     'classParser': function (name) { 
      return (new RegExp("(^|)" + name + "(|$)")); 
     }, 
     'getParser': /^(#|\.)?([\w\-]+)$/ 
    }, 
    'typeOf': typeOf, 
    'hasOwnProperty': function (obj, prop) { 
     return obj.hasOwnProperty(prop); 
    }, 
    'forEach': (function(config){ 
     function (arr, fn, scope) { 
      scope = scope || config.win; 
      for (var i = 0, j = arr.length; i < j; i++) { 
       fn.call(scope, arr[i], i, arr); 
      } 
     } 
    })(this.config) 
} 
+0

虽然它不会对我所做的事有用,但是由于我欣赏另一种处理方法(从来不知道它可能派上用场),所以评价一下。非常感谢答案先生。 – Akidi 2010-06-09 08:18:16