Your example combines three of the four ways in which to invoke a function.
Constructor Invocation
var it = new vm();
Inside of function
vm
, this
refers to the object instance you are returning. This is expected.
Method Invocation
it.pub();
Inside of function
pub
, this refers to the same object instance as is referenced by it
. Again, this is expected.
Function Invocation
pri();
Inside of function
pri
, this
refers to the global object. This is not expected, and is considered to be a mistake in the JavaScript language. The 'pub' function was invoked with the method invocation pattern, and so it is natural to assume the this
should always point to the current function/object when used inside it.
One remedy is to store your returned object in a local variable inside the vm method, and then due to scoping, pub
and pri
methods will be able to reference the object instance safely.
function vm() {
var pub = function () {
alert("from pub: " + that);
pri();
},
pri = function () {
alert("from pri: " + that);
};
var that = {
pub: pub,
pri: pri
};
return that;
}