2010-05-31 111 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