473,406 Members | 2,956 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,406 software developers and data experts.

Is a closure in this code redundant?

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',
onComplete: function(ajaxResponse) { closure.doStuff(ajaxResponse); }
});
(snip)

When you create a function inside a function like this I know a closure
is created but what I don't understand is how this closure is used in
the above example. I've only seen examples where a reference to the
first function is returned so that it can be invoked again at a later
time with the same local variables as were created initially.

However in the above a callback mechanism is used when executing
doStuff() and the function reference would appear to be a local
reference to the inner function (onComplete)

i.e. isn't a closure redundant in the above code?

What am I not understanding here?
Nov 28 '06 #1
9 1601
User1014 wrote:
i.e. isn't a closure redundant in the above code?

What am I not understanding here?

You're absolutely right. Closure is redundant. You SHOULD be able to
do this.doStuff(ajaxResponse). However javascript has a few odd
idiosyncrasies and one one is that to call another procedure inside the
object in this manner you very often times need a variable like closure
to make the call.

Often when browsing object-oriented javascript code you'll find this
workaround expressed as such:

var that=this;

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 28 '06 #2
User1014 wrote:
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',
onComplete: function(ajaxResponse) { closure.doStuff(ajaxResponse); }
});
(snip)

When you create a function inside a function like this I know a closure
is created but what I don't understand is how this closure is used in
the above example.
It allows the call-back function used to handle the XML HTTP response
to call a method of a specific object instance.
I've only seen examples where a reference to the
first function is returned so that it can be invoked again at a later
time with the same local variables as were created initially.
That is what this example is doing, though it is doing it in order to
mitigate significant design flaws in the library that contains
Ajax.Request.
However in the above a callback mechanism is used when executing
doStuff() and the function reference would appear to be a local
reference to the inner function (onComplete)

i.e. isn't a closure redundant in the above code?
No it is not. The function object will know nothing about the object
referred to by - this - at the point when it was defined later on when
it is called, so if it needs to refer to that object instance it needs
another way of referencing it.
What am I not understanding here?
Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).

Richard.

Nov 28 '06 #3
* Richard Cornford wrote:
It allows the call-back function used to handle the XML HTTP response
to call a method of a specific object instance.
I don't see how the code is different to:

this.doStuff(ajaxResponse);

Excuse my ignorance but I'm from a C# background and am obviously
missing something in how local variables and functions on the stack are
retained via the closure mechanism.
>What am I not understanding here?

Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).
No I've not heard that before about Prototype. Can you suggest an
alternative?
Nov 28 '06 #4
User1014 wrote:
* Richard Cornford wrote:
>It allows the call-back function used to handle the XML HTTP response
to call a method of a specific object instance.

I don't see how the code is different to:

this.doStuff(ajaxResponse);
There is an error in the ECMAScript standard which causes this to be bound to
the wrong value. In this case, this will be bound to the global object, not to
the object of interest.

The workaround is to assign this to a variable of the outer function, something like

var that = this;

Then in the inner function we can safely write

that.doStuff(ajaxResponse);

http://javascript.crockford.com/
Nov 28 '06 #5
User1014 wrote:
* Richard Cornford wrote:
It allows the call-back function used to handle the XML HTTP response
to call a method of a specific object instance.

I don't see how the code is different to:

this.doStuff(ajaxResponse);

Excuse my ignorance but I'm from a C# background and am obviously
missing something in how local variables and functions on the stack are
retained via the closure mechanism.
Javascript derives its - this - values form how a function is called,
dynamically at the point of calling it. When the function in question
is called (and no matter how it is called) there is no mechanism in
that context that will refer to the specific object instance in
question, so the function object itself has to know how to refer to the
object instance. It does that through the scope chain of the function,
by referring to the value assigned to - closure -.

<URL: http://jibbering.com/faq/faq_notes/closures.html >
>>What am I not understanding here?

Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).

No I've not heard that before about Prototype. Can you suggest an
alternative?
The best starting point for that answering that sort of question is an
understanding of the context in which the end result is to be used, and
what the end result is supposed to do. No blanket "use this" or "use
that" advice given without that information is good advice.

Richard.

Nov 28 '06 #6
* Richard Cornford wrote:
Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).
This statement does worry me a little because we use ProtoType quite
extensively. Is it really all three of these things that you describe??

The last one worries me the most.
Nov 30 '06 #7
User1014 wrote:
* Richard Cornford wrote:
>Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).

This statement does worry me a little because we use ProtoType quite
extensively. Is it really all three of these things that you describe??
The last is a question of opinion (mine is expressed above), the others
are objective facts.
The last one worries me the most.
OK.

Richard.

Nov 30 '06 #8
User1014 said the following on 11/30/2006 11:07 AM:
* Richard Cornford wrote:
>Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).

This statement does worry me a little because we use ProtoType quite
extensively. Is it really all three of these things that you describe??
Absolutely.
The last one worries me the most.
It should.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 30 '06 #9
* Richard Cornford wrote:
User1014 wrote:
>* Richard Cornford wrote:
>>Hard to say. I can assume that you don't understand how very poor the
Prototype.js library is (being non-cross-browser, non ECMAScript
compliant, and ludicrously deigned).
This statement does worry me a little because we use ProtoType quite
extensively. Is it really all three of these things that you describe??

The last is a question of opinion (mine is expressed above), the others
are objective facts.
>The last one worries me the most.

OK.

Richard.
We have had problems when using ProtoType and the YUI grid together.
That's about all so far......
Nov 30 '06 #10

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

Similar topics

0
by: Dave Benjamin | last post by:
Here are some more ideas for how to implement a statement-friendly code block syntax in Python. Hopefully more "Pythonic" (that is, of or pertaining to those features noticably reminiscent of...
1
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...
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...
0
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
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()
3
by: Steven W. Orr | last post by:
This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global...
4
by: LAN MIND | last post by:
?
4
by: JavascriptProgrammer | last post by:
In the following code: ----------------------- function get() { return function() { alert(x); } }; function foo(s) { var x = s; this.getX = get();
2
by: Andrey Fedorov | last post by:
Is the scope of a closure accessible after it's been created? Is it safe against XSS to use closures to store "private" auth tokens? In particular, in... ....can untrusted code access...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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,...
0
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,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.