I've been using the Revealing Module pattern in my Javascript lately to help structure my code and everything has gone well. However, I'm a bit confused by this code snippet:
function vm() {
var pub = function () {
alert("from pub: " + this);
pri();
},
pri = function () {
alert("from pri: " + this);
};
return {
pub: pub,
pri: pri
};
}
var it = new vm();
it.pub();
it.pri();
When I call pub()
and pri()
directly, this
refers to the current instance of vm
. However, when I call pri()
from within pub()
suddenly this
has reverted to referring to the global window object. I thought one of the objectives of the revealing module pattern was to remove the issues with this
but it appears that when calling a function from within another function I'm losing the value of this
.
Does anyone know why this if and if there's a way to get this to work without having to pass references to the current object around?