I wanted to take a minute and talk a little about Javascripts scope and more importantly go through a couple examples.
In the first example, we will add a closure to our constructor function and then call it.
-
-
var scopeTest = function(a) {
-
function foo() {
-
alert(a);
-
}
-
foo();
-
}
-
-
var test = new scopeTest(1); //Will alert "1"
-
-
In this example we will create a method foo() and a method bar() to our scopeTest object. The foo method will simply alert the value “a” the bar method will add 1 to var a and alert.
-
-
var scopeTest = function(a) {
-
this.foo = function() {
-
alert(a);
-
}
-
this.bar = function(){
-
var a = a + 1;
-
alert(a)
-
}
-
}
-
-
var test = new scopeTest(1);
-
test.foo(); // will alert "1"
-
test.bar(); // will alert "NaN"
-
What happened there is, once we say “var a” inside the scope of the method bar. It ignores the variable “a” in the scope of our “scopeTest” constructor function.
In the final test for this example, we add a method via “prototype”
-
-
var scopeTest = function(a) {
-
this.foo = function() {
-
alert(a);
-
}
-
}
-
-
scopeTest.prototype.bar = function() {
-
alert(a);
-
}
-
-
var test = new scopeTest(1);
-
test.foo(); // Will alert 1
-
test.bar(); // Will have an error because a is undefined
-
