Ok, so I thought I understood this (no pun intended), but apparently not.
var Constructor = function () {
var internalFunction = function () {
return this === window;
};
this.myMethod = function () {
alert(internalFunction());
};
};
var myObj = new Constructor();
myObj.myMethod();
This alerts true
. Why can't the internal function see this
as the object? Instead I have to use alert(internalFunction.call(this));
in myMethod
.
Edit: I was looking for an explanation as to why this
is assigned in that way, not workarounds such as var self = this;
, etc. Sorry if I didn't make that clear.
this
is not bound until the function is called and is dependent on how the function is called. You could think of it as an extra parameter implicitly passed to the function.In this case, the problem is that you're calling
internalFunction
usinginternalFunction()
. Thethis
value is set either by calling a function as a method (as infoo.bar()
orfoo["bar"]()
) or by settingthis
explictly viacall()
orapply()
. Your call is doing neither sothis
reverts to the global object.The simplest way to achieve what you want in this case while keeping
internalFunction
private is to store a reference tothis
inside the constructor function:Because of functional scoping rules,
this
is reassigned inside each function... I would store a copy of your object asself
and use it accordingly...Should give you the output you expect.
SIDENOTE
This is a fairly precarious practice that javascript has created, mainly because if you forget the
new
keyword when usingConstructor
, you will getthis
referring to thewindow
(god) object so you'll be attachingmyMethod
to the window without warning.There are five ways to call a function in JavaScript. The value of
this
depends on which you choose:myFunction()
). No explicit value forthis
is given. The value ofthis
will be the default object (window
in a browser).obj.myFunction()
). The value ofthis
is the object on which the method was invoked (obj
in this case).call
method (e.g.myFunction.call(obj)
). The value ofthis
is provided explicitly (in this caseobj
).apply
method (e.g.myFunction.apply(obj)
). The value ofthis
is provided explicitly (in this caseobj
).new MyFunction()
). The value ofthis
is a newly-created object provided by the runtime.Each of the five is explained in more detail here:
Its a scope issue try something like: