473,890 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The interesting question on Closure

dmjpro
2,476 Top Contributor
Today i looked at JavaScript closures. There i came across a thing closure comes in when an inner function defined inside an outer function. So when outer function exits and returns the inner function reference then a hidden reference returns along with the reference of inner function.

Now my question is when that hidden reference created? And the hidden reference have the references of all local variables of outer function. Now my second question..
If any variables local to a loop scope are also being referenced by hidden pointer. But those variables get destroyed after loop scope ends up, how it gets handled?

Now have a look at code snippet....
Expand|Select|Wrap|Line Numbers
  1. function outer(){
  2. var var1 = some_value;
  3. var inner = function(){some_code;}
  4. return inner;
  5. }
  6.  
Here when inner returns then a closure of outer's local variables get created.
so the reference of inner variable being referenced by hidden pointer or only variable var1?

I think experts can get my point of view.
Please answer these questions!
Aug 6 '08 #1
4 1314
rnd me
427 Recognized Expert Contributor
Today i looked at JavaScript closures. There i came across a thing closure comes in when an inner function defined inside an outer function. So when outer function exits and returns the inner function reference then a hidden reference returns along with the reference of inner function.
1. loops don't have scope in javascript.
2. your example function does not produce a closure, no variable name is reused to be preserved.


here is a simple closure example, showing how functions preserve scope.

Expand|Select|Wrap|Line Numbers
  1.     var name = "bob";
  2.  
  3.   function demoClosures(){
  4.     var name = "fred";
  5.     setTimeout(  "alert('not closed: hello '     +   name )"  , 100);
  6.     setTimeout(  function(){ alert('closed: hello '+ name )} , 500);
  7.   }
  8.  
  9.   demoClosures();
notice how name is (en)closed in the function-based setTimeout.
Aug 6 '08 #2
dmjpro
2,476 Top Contributor
1. loops don't have scope in javascript.
2. your example function does not produce a closure, no variable name is reused to be preserved.


here is a simple closure example, showing how functions preserve scope.

Expand|Select|Wrap|Line Numbers
  1.     var name = "bob";
  2.  
  3.   function demoClosures(){
  4.     var name = "fred";
  5.     setTimeout(  "alert('not closed: hello '     +   name )"  , 100);
  6.     setTimeout(  function(){ alert('closed: hello '+ name )} , 500);
  7.   }
  8.  
  9.   demoClosures();
notice how name is (en)closed in the function-based setTimeout.
OK i checked that there is no scope inside a function .... :-)
Actually i didn't mention that the variable used by my inner function code.
Anyway i can understand and thanks for sharing your knowledge.
Now my question is that which name will be used in inner function; the global one or the enclosed name?
Please explain...
Aug 6 '08 #3
gits
5,390 Recognized Expert Moderator Expert
in your first timeout the construct is evaled later out of the scope of the current function from where it is called so it will alert 'bob', which is your global variable ... the second one closures the value of the local variable name and will alert 'fred' ... ok? :)
Aug 6 '08 #4
rnd me
427 Recognized Expert Contributor
OK i checked that there is no scope inside a function .... :-)
you should check again. functions are the about only thing that has scope in javascript. 1. 2. 3.


to answer your question though, the closest, most-local, variable will be used. it will creep outward looking for matches of the name until get to window (global). .prototype props and methods are checked only if no other match is found.
Aug 6 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

27
2134
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 in mylist: .... setattr(myclass, item, lamdba self: func(self, item))
1
1810
by: Victor Ng | last post by:
Is there a way to preserve the argspec of a function after wrapping it in a closure? I'm looking for a general way to say "wrap function F in a closure", such that inspect.getargspec on the closure would return the same (args, varargs, varkw, defaults) tuple ass the enclosed function. The typical code I'm using is something like this: def wrapFunc(func):
9
2744
by: Mikito Harakiri | last post by:
Transitive closure (TC) of a graph is with TransClosedEdges (tail, head) as ( select tail, head from Edges union all select e.tail, ee.head from Edges e, TransClosedEdges ee where e.head = ee.tail ) select distinct * from TransClosedEdges
7
1883
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 shows the alert. What is the essential reason? function () { alert('hi mom'); }(); function () { alert('hi dad'); }(8); var x=function () { alert('hi bro'); }();
9
1628
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 = new Ajax.Request(this.Url, { method: 'post',
0
1103
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
11
3035
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
2000
by: LAN MIND | last post by:
?
4
1393
by: JavascriptProgrammer | last post by:
In the following code: ----------------------- function get() { return function() { alert(x); } }; function foo(s) { var x = s; this.getX = get();
0
9977
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9816
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11218
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10910
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
8009
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7161
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3268
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.