473,395 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

closure question

In the following code:
-----------------------
function get() {
return function() {
alert(x);
}
};
function foo(s) {
var x = s;
this.getX = get();
}
var f = new foo("hello");
f.getX()
--------------------------

Instead of printing "hello", f.getX() gives a JS error
of ("x is not defined").

Can someone explain Why in detail ?

Sep 24 '08 #1
4 1364
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
Sep 24 '08 #2
On 2008-09-24 06:45, JavascriptProgrammer wrote:
Instead of printing "hello", f.getX() gives a JS error
of ("x is not defined").

Can someone explain Why in detail ?
What you expected would indeed be correct in a dynamically scoped
language, but JavaScript uses lexical scope. Here's a good explanation
of the difference between the two:

http://en.wikipedia.org/wiki/Scope_(programming)
- Conrad
Sep 24 '08 #3
Conrad Lender <cr******@yahoo.comwrites:
On 2008-09-24 06:45, JavascriptProgrammer wrote:
>Instead of printing "hello", f.getX() gives a JS error
of ("x is not defined").

Can someone explain Why in detail ?

What you expected would indeed be correct in a dynamically scoped
language, but JavaScript uses lexical scope. Here's a good explanation
of the difference between the two:

http://en.wikipedia.org/wiki/Scope_(programming)
Correct. And to expand a bit, as far as I know closures are /defined/ to
work on lexicals. You can do similar things with dynamic variables (if
your language supports them) but many of the really interesting uses of
anonymous functions require lexical scope and closures:
function make_closure() {
var i = 0;
return function () { return ++i };
}

var c1 = make_closure();
c1(); // 1

var c2 = make_closure();
c2(); // 1

c1(); // 2
c1(); // etc...
c2();
c1();

See also:
http://en.wikipedia.org/wiki/Closure_(computer_science)

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Sep 24 '08 #4
RobG wrote:
JavascriptProgrammer wrote:
>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. [...]
Because `x' was declared a local variable of the constructor's *execution
context*, it became a property of its *Variable Object*. As became `s', BTW.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Sep 26 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
by: Ted Lilley | last post by:
What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: .... pass >>>def func(self, arg): .... print arg >>>mylist = >>>for item...
7
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that...
9
by: User1014 | last post by:
I'm a javascript noob and have a question concerning some code I've come across that I'm trying to understand. Here is a snippet of the relevant section: (snip) var closure = this; var xhr =...
11
by: Huayang Xia | last post by:
What will the following piece of code print? (10 or 15) def testClosure(maxIndex) : def closureTest(): return maxIndex maxIndex += 5 return closureTest()
4
by: LAN MIND | last post by:
?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.