Skip to content Skip to sidebar Skip to footer

Javascript "this" Variable Confusion

I am currently reading the book 'Javascript: The Good Parts' and was playing with Functions. I produced a test script to test some properties and I am somewhat confused by the resu

Solution 1:

This is how the value of this is determined.

// function casefoo(); // this inside foo will refer to the global object// method case
test.foo(); // this inside foo will refer to test// constructor case
new foo(); // this inside foo will refer to the newly created object

So unless you deal with a method or a constructor this is rather useless.

Solution 2:

outF.inner

points to a variable that is not accessible in that scope from where line of code is.

inner is declared in outterF and it's only accessible in there.

If you used

this.inner = innerF();

it may be accessible (can't test right now)

Solution 3:

'this' is a keyword not a property so you need to reference it as a standalone semantic:

//correct syntax...that gets value of this keywordvar that = this//unusual syntax...that is undefined, unless you explicitly set foo.this earlier
vat that = foo.this; 

Specifically a 'this' value is assigned for every runtime function context (and the global context). It is immutable within a give context. The rules are somewhat complex but the important cases are...

In global context 'this' will always be the global object (e.g. window)

var that = this; //window

When invoked from a method call 'this' will be the receiver of the method call

obj.foo = function() {
    returnthis;
}

obj.foo(); //obj

When invoked from a function call 'this' will be the global object

var obj = {};
obj.foo = function() {
    returnthis;
}

var myFn = obj.foo;
myFn(); //window

You can also use call/apply to set a custom 'this' value within a function context. If you're interested in learning more read this: (no pun :-) ) http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

Solution 4:

outF is [object Window] and doesn't have a "inner" variable, as such if inF = outF.inner, it's undefined

Solution 5:

Note that outF (in the line outF.inner) doesn't refer to outF's scope, but rather the value assigned to outF.

functionMyCtor() {
    this.someVal = function() {
        document.write("someVal's this? " + this);
    };
}

var myobj = newMyCtor();
myobj.someVal();

Gives someVal's this? [object Object] (or whatever), which is what you want.

Post a Comment for "Javascript "this" Variable Confusion"