[英]Javascript and module pattern
我认为我不了解javascript模块模式。
我只是创建此模块:
var mycompany = {};
mycompany.mymodule = (function() {
var my = {};
var count = 0;
my.init = function(value) {
_setCount(value);
}
// private functions
var _setCount = function(newValue) {
count = newValue;
}
var _getCount = function() {
return count;
}
my.incrementCount = function() {
_setCount(_getCount() + 1);
}
my.degreeseCount = function() {
_setCount(_getCount() - 1);
}
my.status = function() {
return count;
}
return my;
})();
var a = mycompany.mymodule;
var b = mycompany.mymodule;
console.debug(a, 'A at beginning');
console.debug(a, 'B at beginning');
a.init(5);
b.init(2);
console.log('A: ' + a.status()); // return 2 (wtf!)
console.log('B: ' + b.status()); // return 2`
错误在哪里? 我以为我的代码将返回给我的不是2的值,而是5。
什么原因?
a
和b
是完全相同的对象。
var a = mycompany.mymodule;
var b = mycompany.mymodule;
您要做的是创建两个具有相同原型的不同对象。 类似于以下内容:
mycompany.mymodule = (function () {
var my = function () {};
my.prototype.init = function (value) {
_setCount(value);
};
my.prototype.incrementCount = ...
// ...
return my;
}());
a = new mycompany.mymodule();
b = new mycompany.mymodule();
a.init(5);
b.init(2);
有关更多信息,请研究“ javascript原型继承”
在JavaScript中,对象是通过引用传递的,而不是复制的。
为了进一步说明,这是代码的简化版本:
var pkg = (function () {
var x = {};
return x;
}());
var a = pkg;
var b = pkg;
您无需创建两个单独的对象,而只能从a
和b
引用pkg
指向的对象。 a
和b
完全相同。
a === b // true
这意味着,调用方法上a
你最终做同样以b
(它指向同一个对象- x
)。
您不想为此使用模块模式。 您需要通常的构造函数+原型。
function Pkg() {
this.count = 0;
};
Pkg.prototype.init = function (count) { this.count = count; };
var a = new Pkg();
var b = new Pkg();
a === b // false
a.init(2);
a.count === 2 // true
b.count === 2 // false
这是有关模块模式的很好的阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.