HTML and CSS Reference
In-Depth Information
Outer this [object Object]
Inner this [object Object]
30
Earlier in this topic I mentioned a fourth way
this
could be defined: inside constructor func-
tions. Within a constructor function
this
refers to the implicitly created object, provided the
function was invoked with the
new
modifier. Without the
new
modifier,
this
becomes the
global object again.
It is worth mentioning one more limitation of JavaScript before completing this section.
JavaScript does not support block level scope. This can be seen in the following example:
function test() {
var a = [1,2,3,4];
for (var i = 0; i < a.length; i++) {
var a = i;
console.log(a);
}
console.log(a);
}
The inner block here uses the same variable name
a
as is used in the outer block. In most
programing languages the two variables named
a
would be different, because they are
defined in different blocks of code. JavaScript does not support block level scoping: it only
supports function level scoping, therefore the line:
var a = i;
overwrites the variable defined here:
var a = [1,2,3,4];
In addition to being limited to functional scoping, JavaScript employs another technique
for all the variables defined within a function called “hoisting”. Before we explain “hoist-
ing”, try to work out why only one of these two functions produces an error when executed:
> function testLocal() {
console.log(j);
var j = 10;
}
> function testGlobal() {