Im working in a sub-module pattern code. Want to create sub-modules with objects literals, the problem is this
for the objects inside the sub-module is MODULE and not my object literal. Any idea?
var MODULE.sub = (function () {
var myObject = {
key: value,
method: function () {
this.key // this = MODULE and not MyObject... :(
}
};
return myObject.method;
}(MODULE));
The
this
keywords value depends on how the function is called. So if you assign that function toMODULE.sub
, and then invoke it asMODULE.sub(…)
, thenthis
will point to theMODULE
of course. If you had invoked it asmyObject.method(…)
, thenthis
would point to that object.So you either should expose the whole
myObject
(like in @BingeBoys answer), or do not export that function and expect it to be a method ofmyObject
. Instead, you could use a bound one:or the explicit equivalent of that
or you would not put the function as
method
on that object at all:Solved... just return a function in MODULE.sub calling the public method. I don't know if is the best approach
This works for me:
Then call it:
You were only returning the method and not the key so "this" would be undefined. You could keep it private if you want like this and pass key in as a var: