use*_*276 5 javascript singleton constructor instance
你可以将实例命名为与构造函数名称相同吗?
var myFunc = new function myFunc(){};
Run Code Online (Sandbox Code Playgroud)
?
看起来,这将使用新实例替换Function对象...这意味着这是一个很好的Singleton.
我没有看到有人使用这个,所以我想,这有些缺点,我不知道...
有什么想法吗?
YES...
However, it does look weird that you're creating a named function but never refer to it by name.
The more common pattern(s) I've seen are
function MyClass(){
this.val = 5;
};
MyClass.prototype.getValue = function() {
return this.val;
}
MyClass = new MyClass();
Run Code Online (Sandbox Code Playgroud)
But when people do that I wonder why they don't just use a literal object
var MyClass = {
val: 5,
getValue: function() {
return this.val;
}
}
Run Code Online (Sandbox Code Playgroud)
And I would even prefer to use the module pattern here
var MyClass = (function(){
var val = 5;
return {
getValue: function() {
return val;
}
};
})();
Run Code Online (Sandbox Code Playgroud)
Disclaimer
Now whether the singleton pattern should be used, that's another question (to which the answer is NO if you care about testing, dependency management, maintainability, readability)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |