I have the following error when running the page below:
"this.testpublic is not a function"
test = function() {
var testprivate = function() {
this.testpublic();
}
this.testpublic = function() {
console.log('test');
}
testprivate();
}
new test();
Apparently when testprivate
is called, "this" starts pointing to "window" instead of the object.
Shouldn't JavaScript preserve "this" context when within the same object?
The problem is that
this
actually never was referring to thetest
object to begin with. It was always referring to the nearest enclosing object -- which in this case iswindow
.This works because, as I understand it,
this
is determined at call time -- and it is locked into the nearest "enclosing" object*, unlesscall()
orapply()
is used.*
There is probably a much better word for this, but I don't know it off the top of my head. If someone knows, please enlighten us all :-)No, it shouldn't. The function merely defines scope.
When you call
foo.bar()
thenthis
(insidebar()
) isfoo
. Since there is no explicitfoo
in this case, it iswindow
by default.(
this
is handled differently when thenew
keyword is in play, but it isn't for that call)It is as Sean says: you aren't actually creating a new reference to an object (creating a this context), because you are simply calling the constructor - not utilizing the constructor to create a new object. If you use the new keyword, it works just peachy.
Since the scope of test() is window when you call it, any function called from within test() will execute in the window scope.
By using the new keyword, you are allocating a new object to memory - and creating a new scope.
For example, try this in firebug:
You will see this result:
The Function base object has a method, call(), which as outlined by Craig, allows you to explicitly specify which scope the function should run in:
This is, however, not the preferred way of doing things, as you aren't actually creating a new object here, and typeof myFunction will still return "function" instead of "object" - when you really just wanted to create an object.
You need to manipulate the context when calling testprivate. You can use function.call to override the scope of the function. Try this: