我有一些关于JavaScript的问题,我需要确定一下。为了帮助,我有一个简单的类definiton我写:设计一个正确的方式
var dataSource = function (src, extension) {
return {
exists: function() {
// function to check if the source exists (src *should* be an object
// and extension should be a string in the format ".property.property.theSource".
// this function will return true if src.property.property.theSource exists)
},
get: function() {
// function will return the source (ex: return src.property.property.theSource)
}
}
}();
问题:
1)在我目前的JavaScript的理解,调用数据源()将创建自己的副本的新对象存在()和get()方法的。我对么?
2)有没有办法写这个,所以如果我创建了1,000,000个dataSource对象,我只需要每个函数都有一个副本?
3)我应该关心(2)吗?
我还可以让`src`和`extension`保持私密吗? – JustcallmeDrago 2011-01-28 07:59:19
@JustCallmeDrago,你一直在做什么 - 构建闭包 - 是模拟私人变量的唯一便携方式。根据我的经验,用`_`作为前缀并在你的组织中有一个不依赖`_`前缀变量的约定在大多数情况下就足够了 – tobyodavies 2011-01-28 08:07:27
@Toby:啊。这就是我一直在寻找的。如果你将这个区别添加到你的答案中,我会接受它! – JustcallmeDrago 2011-01-28 08:21:24