简体   繁体   English

Javascript和模块模式

[英]Javascript and module pattern

i think i did not understand javascript module pattern. 我认为我不了解javascript模块模式。

I just create this module: 我只是创建此模块:

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`

Where is the mistake? 错误在哪里? I thought that my code would have returned to me not 2 value, but 5. 我以为我的代码将返回给我的不是2的值,而是5。

What's the reason? 什么原因?

a and b are the exact same objects. ab是完全相同的对象。

var a = mycompany.mymodule;
var b = mycompany.mymodule;

What you want to do is create two different objects which have the same prototype. 您要做的是创建两个具有相同原型的不同对象。 Something similar to this: 类似于以下内容:

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);

For more info, research "javascript prototypal inheritance" 有关更多信息,请研究“ javascript原型继承”

In JavaScript, objects are passed by reference, not copied. 在JavaScript中,对象是通过引用传递的,而不是复制的。

To explain further, here is a simplified version of your code: 为了进一步说明,这是代码的简化版本:

var pkg = (function () {
  var x = {};
  return x;
}());

var a = pkg;
var b = pkg;

You do not create two separate objects but only reference the object pointed at by pkg from both a and b . 您无需创建两个单独的对象,而只能从ab引用pkg指向的对象。 a and b are exactly the same. ab完全相同。

a === b // true

This means that calling a method on a you are ultimately doing the same to b (it points to the same object— x .) 这意味着,调用方法上a你最终做同样以b (它指向同一个对象- x )。

You don't want to use the module pattern for this. 您不想为此使用模块模式。 You want the usual constructor+prototype. 您需要通常的构造函数+原型。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM