且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Javascript / Coffeescript中如何在测试中模拟出模块的公共变量?

更新时间:2023-02-14 18:20:02

您想在这种情况下使用this,

You want to use 'this' in that case,

doSomething = function() {
    return alert(this.state);
};

在你的代码中,'state'指的是未定义的变量然后返回一个包含新的'state'属性的对象。你不需要第一个'state'变量,而只需要返回的对象中的属性。

In your code, 'state' refers to the variable (via closure) which is undefined. You then return an object containing a new 'state' property. You don't need the first 'state' variable, but only the property in your returned object.

'this'在doSomething中指的是任何对象。在test3中,doSomething引用返回的对象,'state'设置为undefined。一旦在test3中设置状态,对象的'state'属性就不再与test2中的私有变量'state'相同 - 它在test3中被覆盖。

'this' in doSomething refers to whatever object it is a part of. In test3, doSomething refers to the returned object with 'state' set to undefined. Once you set state in test3, the object's 'state' property is no longer the same as the private variable 'state' in test2-- it is overwritten in test3.

基本上,你不需要你想要的效果模块模式,有一个更容易的方法:

Essentially, you don't need the module pattern for the effect you desire, there's a much easier way:

root.test2 = {
    state: void 0,
    doSomething: function() {
        return alert(this.state);
    }
};

http://jsfiddle.net/rMJs5/

UPDATE ::我忘记了咖啡部分:

UPDATE:: I forget all about the Coffee part:

root = exports ? this
root.test2 = (->
  doSomething = -> alert this.state
  return {
    state: undefined
    doSomething: doSomething
  }
)()

或者:

root = exports ? this
root.test2 = {
    state: undefined
    doSomething: -> alert this.state
}