Possible Duplicate:
Javascript: Do I need to put this.var for every variable in an object?
I’m struggling to understand functions and objects in javascript. It is said that also functions are objects and objects are kind of “associative arrays” i.e. collections of key-value pairs. I understand that if I write
function myFunction() {
var value = 0;
}
alert(myFunction.value); //then this gives me "undefined"
because variables have function scope. But if I write
function myFunction() {
this.value = 0;
}
alert(myFunction.value); //then this gives me "undefined" too.
But finally, If I write
function myFunction() {
this.value = 0;
}
myFunction.value = 0;
alert(myFunction.value); //then this gives me 0
So I can give myFunction property “value” but from “outside”. Can someone explain what is going on and why this.value = 0; doesnt create property “value”.
Let’s look at all three cases individually:
Here, you’re declaring a variable in the function’s scope. Each time the function is called, the variable will be created (and memory will be allocated). When the function returns, the variable goes out of scope – the variable
valueis flagged and will be GC’ed. The scope can’t be accessed from a scope “higher” than this function’s scope… if this function defined a function within its scope, that function will have access to the variablevalue(look into closures for more details). Bottom line: the variable only exists as when the function is called, and won’t exist after the function returns.Here, you’re defining a function that could be a constructor, a method, an event handler or a combination of all of the above.
thisis a reference that will point to the context in which the function is called. This contexted is determined “ad hoc” and may vary:In the last case:
It wouldn’t have made any difference if you’d have written this:
Because, as I explained above:
thisreferences whatever the context is at the time the function is called. This needn’t bemyFunction, in fact: more often than not it won’t be:If you want to access a function’s properties inside that function, the easiest way is to reference that function like any other object:
Caution:
Just a friendly warning: it’s not very safe to use
thisin functions without checking for globals… If a function is called without an explicit context, JS uses the global (window) object by default. This means that every line that assigns a property to whatever objectthishappens to be pointing too will set a global variable:A few ways to prevent the global object from being cluttered with globals: