2011-12-28 85 views
2

我想知道是否有方法将名称空间保留在Javascript对象中的函数内。将名称空间保留在对象函数范围内

首先,让我们设置一些东西。假设我们在名称空间FooBar中有一个类(好,接近一个类获得的类)Foo。然后在全局命名空间(窗口),我们有一流的酒吧,实例化美孚的,所以...

FooBar.Foo = function() { 

} 

function Bar() { 
    this.init(); 
} 

Bar.prototype = { 
    init: function() { 
    this.foo = new FooBar.Foo(); 
    } 
} 

目前我有两个系统把东西放进范围: 1.使用(“FooBar的” )和unusing(“FooBar”)这些函数将引用移动到全局名称空间内外的给定名称空间的内容。 2. with(namespace(“FooBar”)){}这使用普通的行为,给它一个对象包含对名称空间中包含的所有内容的引用。 所以现在,我必须在每个函数中使用这些方法之一来将名称空间带入范围。我想看看是否有类被声明时定义这些并让他们仍然在范围只是这个班因某种封闭的方法...

FooBar.Foo = function() { 

} 

using("FooBar"); 

function Bar() { 
    this.init(); 
} 

Bar.prototype = { 
    init: function() { 
    this.foo = new Foo(); 
    } 
} 

unusing("FooBar"); 

所以,是的,是甚至可能这样的事情,还是我坚持把这些事情经常纳入范围?

回答

1

这是一种可怕的。我会建议使用像RequireJS这样的现代模块系统。 My friend put together a nice presentation on the evolution and use of module systems in JavaScript。他们是JS对命名空间的回答。

您的代码将是这个样子:

// FooBar.js 
define(function (require, exports, module) { 
    exports.Foo = function() { }; 
}); 

// Bar.js 
define(function (require, exports, module) { 
    // This is kind of like "using FooBar" in other languages. 
    var Foo = require("FooBar").Foo; 

    exports.Bar = function() { 
     this.init(); 
    }; 
    exports.Bar.prototype = { 
     init: function() { 
      this.foo = new Foo(); 
     } 
    }; 
}); 

// elsewhere.js 
define(function (require, exports, module) { 
    var Foo = require("FooBar").Foo; 
    var Bar = require("Bar").Bar; 

    console.log(new Foo()); 
    console.log(new Bar()); 
}); 
+0

这是一个很多额外的东西我在做什么,而不是完成我需要什么。鉴于目前的系统,这可以完全相同地实施。 – Ixonal 2011-12-28 02:20:26

+0

部分原因在于你是否希望其他JS程序员能够理解你的代码。这个模块系统是标准的,而你提出的东西会让人瞪大眼睛,想知道你的脑子里发生了什么(弄乱像这样的全球范围就是疯狂!),并立即强烈要求重构这个疯狂的东西。 – Domenic 2011-12-28 02:24:39

+0

+1 - 这个回答的开头让我大笑 – 2011-12-28 03:27:22