Function code is code in the body of a function. The scope of function code is not trivial. It includes:
- The variable object of the calling code's execution context. This object includes all variables that were defined up to the point where the function (or its outer function) is called.
- The variable object of the outer function, if there is an outer function.
- The global object which is the browser window object.
- The arguments object which includes all passed parameter values.
A new variable object is created and initially has only the declared arguments of the function. Normally, the this object is the global object (the browser window object). The most obvious exception is when the function is a method of an object. In this case, the this value is the object that it is a method of. Let's examine an example. The function standAlone() just prints the value of this.location, where this is the browser window object. The function also prints window.location to show you that this is window. Try it.
The function ObjectConstructor() is an object constructor. We create a new object, newObject, with this constructor. Inside the constructor, the value of this.location is now undefined because this is the object newObject and not the browser window object. Try it
Here is the code:
function standAlone() {
alert("this.location is " + this.location);
alert("window.location is " + window.location);
}
function ObjectConstructor() {
alert(this.location);
}
function createObj() {
var newObject = new ObjectConstructor();
}
standAlone();
People who read this tip also read these tips:
Look for similar tips by subject:
|