You want to use 'this' in that case,
doSomething = function() {
return alert(this.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' 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);
}
};
UPDATE:: I forget all about the Coffee part:
root = exports ? this
root.test2 = (->
doSomething = -> alert this.state
return {
state: undefined
doSomething: doSomething
}
)()
Or, simply:
root = exports ? this
root.test2 = {
state: undefined
doSomething: -> alert this.state
}