On Sep 24, 2:45*pm, JavascriptProgrammer <nowh...@nowhere.comwrote:
In the following code:
-----------------------
function get() {
return function() {
* * * * alert(x);
The x here is not declared, so when the function is called it will go
looking for it on its scope chain.
* * * * }};
function foo(s) {
* * * * var x = s;
x here is a local variable of the function foo.
* * * * this.getX = get();
* * * * }
var f = new foo("hello");
f doesn't have an x property, it was declared as a property of the
constructor. The function get() was called from inside the
constructor, but since it's declared outside the constructor, it
doesn't have a closure to x.
f.getX()
--------------------------
Instead of printing "hello", f.getX() gives a JS error
of ("x is not defined").
'cos it ain't. :-)
Move the function declaration for get inside the constructor, or use a
statement:
function foo(s) {
function get() {
return function() {
alert(x);
}
}
var x = s;
this.getX = get();
}
or, for simplicity's sake:
function foo(s) {
this.getX = function() {
alert(s);
}
}
Can someone explain Why in detail ?
There is no closure. Closures are created by how you declare a
function, not by how you call it. To create a closure, you declare a
function (or use a function expression) inside another function:
function foo() {
var x;
function bar() { // Create a closure
alert(x); // Use it to access foo's x
}
}
--
Rob