In some of my Javascript objects I find that my this pointer is correct – these are new Func() -type objects – when created, but in the assigned methods it can be wrong.
function Confused() {
console.log("checking",this==window,"is always false");
this.method = function() {
console.log("checking",this==window,"is true for some funcs but not others");
};
};
On some calls to (new Confused()).method() – it seems to have lost it’s this pointer. The times this happen seem dependent on the function, rather than random; its something in the code around how I’m creating classes that is causing this.
An example is online at http://williame.github.com/barebones.js/ and the member callback G3D._file_loaded has a wrong this pointer when called sometimes.
Why, and how do I fix it?
There are 4 ways to use a function in Javascript
what each of these does is change what the content of
thisis :In your case
this == windowwhen you call the function directly (Confused()) but if you call using new (new Confused()) then it will be the new object you are creating.