Function return function???

S

strout

function F(e)
{
return
function(){P(e)}
}

Can anybody tell me what the code is doing?

If return another function all in a function I would do
function F(e)
{
return P(e)
}

Is it defining another function? I don't recall other languages can
define another function inside one function. Why would the programmer
do this?
 
S

strout

what i am trying to ask is what's this code doing

function F(e)
{
return
function(){P(e)}
}
 
L

Lee

strout said:
what i am trying to ask is what's this code doing

function F(e)
{
return
function(){P(e)}
}

It creates a new function and returns it.


document.getElementById("alpha").onclick=F(1178);

Clicking on alpha will now execute P(1178)
 
S

strout

Well, it's from Gmail Javascript file. Gmail is generated by pure
javascript from backend.

Guess I have to write some code to figure it out myself.
 
S

strout

So you will have to declare P something like

function P(e)
{
alert(e);
}

So basically it's same as
document.getElementById("alpha").onclick=P(1178);

What's the catch here?
 
Y

Yann-Erwan Perio

Jarmo wrote:

[closures]
To do unspeakable things that no-one will ever be able to support ;-)

Then spread the damn thing so that every professional be aware of it and
use it everywhere; javascript's real power lies hidden in closures:)

While it'd be true that the concept and resulting code may look obscure
to programmers unfamiliar with the functional paradigm, closures still
remain fully supported by javascript and IMHO offer programmers willing
to use them (that is, using the js paradigm to its full potential),
quite a formidable asset in large apps designing.

Of course you're right, most js programmers have never heard about the
techniques and keep using "simple" javascript - however would you trust
maintainers unable to understand properly-documented closures-based code
to be skilled enough to offer anyway an acceptable level of quality in
application maintenance?


Cheers,
Yep 'closures aren't that hard'.
 
Y

Yann-Erwan Perio

strout said:
So basically it's same as
document.getElementById("alpha").onclick=P(1178);

It's not the same, in Lee's example the function returns a function,
your example doesn't return anything but undefined. When the click event
is dispatched you'll have no handler to capture it.
What's the catch here?

The basic thing is that the inner function can access the outer function
local variables, even after the outer function has returned the inner
function. This permits to build private/public scopes, see the articles
that Jarmo has advised if you want to dig the matter further.


Regards,
Yep.
 
M

Michael Winter

strout said:
function F(e)
{
return
function(){P(e)}
}

Can anybody tell me what the code is doing?

As is, nothing. It is a breach of the grammar rules for a return
statement to be followed by a line terminator. The code would be
parsed as:

function F(e) {
return;
function() {P(e);};
}

Notice the added statement-terminating semicolons. The function
expression would never be evaluated.

Pedantry aside, it does what you think it does: creates a function
object via a function expression and returns that object. However, the
nature of the creation of that object is special. Namely, the value of
e passed to F will be passed to P any time the returned function is
called. Consider:

function A(n) {
return function() {alert(n);};
}

var B = A(1),
C = A(2);

The variables B and C now contain references to function object
created by the call to A. No matter when B or C is called, the former
will display 1 and the latter, 2. This is true even the initial calls
to A have returned and (you might have thought) the value of n is of
no relevance. If you care to read the cited explanations, you'll see
that in fact the value of n does continue to exist in the execution
context of B and C, allowing them to refer to, and display, those values.

[snip]

Hope that helps,
Mike
 
J

Jarmo

Yann-Erwan Perio said:
Jarmo wrote:

[closures]
To do unspeakable things that no-one will ever be able to support ;-)

Then spread the damn thing so that every professional be aware of it and
use it everywhere; javascript's real power lies hidden in closures:)

I've yet to see a compelling need for closures in JavaScript but I'm open to
suggestion. Bring it on ;-)

Personally, I'd have preferred them to have designed variable scoping
correctly and at least provided an option for strong types then I'd have a
lot more enthusiasm for the more esoteric features.
 
A

Anthony Borla

strout said:
Well, it's from Gmail Javascript file. Gmail is generated by pure
javascript from backend.

Guess I have to write some code to figure it out myself.

I find writing up quick 'code doodles' to be the key to understanding code,
thereby gaining insight into new / unknown techniques.

Some such doodles below - adjust to suit.

Cheers,

Anthony Borla

// --------- Function Doodles -----------

// Using WSH as host

function newline()
{
WScript.Echo();
}

function showMeta(name, arg)
{
WScript.Echo("Item " + name + " metadata:");
WScript.Echo("Value -> |" + arg + "|");
WScript.Echo("Type -> |" + typeof arg + "|");
}

function F1(e)
{
// Implicit return of undefined
}

function F2(e)
{
// Value of of argument 'e' returned
return e;
}

function F3()
{
// Return of function 'G' definition [note:
// name not really needed]
return function G(e) { return e * 2; };
}

function F4(e)
{
// Return of function 'G' application [note:
// name not really needed]
return function G(f) { return 2 * f; }(e);
}

var r, r1;

// Call functions:

// 'F1' arg = 5, return value = undefined
r = F1(5);
showMeta("F1:r", r);


// 'F2' arg = 5, return value = 5
r = F2(5);
newline(); showMeta("F2:r", r);


// 'F3' arg = N/A, return value = function
// 'r1' arg = 5, return value = 10 [application
// of returned function]

r = F3();
newline(); showMeta("F3:r", r);

r1 = r(5);
newline(); showMeta("F3:r1", r1);


// 'F4' arg = 5, return value = 10 [application
// of function]
r = F4(5);
newline(); showMeta("F4:r", r);
 
A

Anthony Borla

Yann-Erwan Perio said:
Jarmo wrote:

[closures]
To do unspeakable things that no-one will ever be able
to support ;-)

Then spread the damn thing so that every professional be
aware of it and use it everywhere; javascript's real power
lies hidden in closures:)

I suppose another way to achieve this is to paste links to Douglas
Crockford's site *everywhere* ;) !
While it'd be true that the concept and resulting code may
look obscure to programmers unfamiliar with the functional
paradigm, closures still remain fully supported by javascript
and IMHO offer programmers willing to use them (that is,
using the js paradigm to its full potential), quite a formidable
asset in large apps designing.

It's a pity so many developers out there do not learn such techiques. Even
if not used in day-to-day developemnt, they would at least offer a developer
an addeded insight into the development process. It seems to me, however,
that unless a developer completes a Scheme-based course in high school or
college [let's be honest: what professional developer would shell out $$$ to
enrol in such a course], then the chances of learning about closures, or
other metaprogramming techniques, is marginally greater than zero.

What's also a pity is that there is obviously room for the use of these more
advanaced techniques, but the mechanisms by which they are supported in
popular developer languages are either overly complex [think C++ templates]
or cumbersome to use [think Java reflection; introspection in Python etc].
Yet, rather than looking at alternatives, developers struggle with these
problems, and assume that development *should* be a such struggle.
Of course you're right, most js programmers have never
heard about the techniques and keep using "simple" javascript
- however would you trust maintainers unable to understand
properly-documented closures-based code to be skilled
enough to offer anyway an acceptable level of quality in
application maintenance?

The irony is that such power is present in what is so, all-too-commonly,
regarded as a 'toy' language. And that it [JavaScript] has been so-marketed
is one of those sad accidents of history.

Still, it seems to me that hope for JavaScript to become more than a browser
client language seems to be with any efforts to produce bytecode compilers.
Perhaps standardised versions targeting the .NET or JVM platforms, together
with beefed up host access capabilities [e.g. better access to system
services] ?
Cheers,
Yep 'closures aren't that hard'.

And the even greater irony is that closures have been around since around
the 1960's with LISP [no wonder many LISPer's often come across as smug and
superior - they've had all this 'power' at their disposal for so long ;) !]

Cheers,

Anthony Borla
 
S

strout

Thanks.
I don't have much programming experience but I do have taken full
cirriculmn in CS. This is my first time read about 'closure'.

I am wondering what it takes to be able to write complex code, for
example, the one I found from Google's Gmail. I always though
Javascript is easy until I begin to study Google's JS file. Most of my
time I use Microsoft IDE. C# and VB.net. I think it's great because you
can put more time on thinking and analysis work flow. IDE is taking
take of many things for you.

I don't know if it's a good trend or not. Programmers become more
productive? or maybe not.

:(

strout
 
R

RobG

Jarmo wrote:
[...]
I've yet to see a compelling need for closures in JavaScript but I'm open to
suggestion. Bring it on ;-)

Personally, I'd have preferred them to have designed variable scoping
correctly and at least provided an option for strong types then I'd have a
lot more enthusiasm for the more esoteric features.

I'm a newbie to JavaScript, but find it a fascinating language.
Your request for a compelling reason for closures and subsequent
comment on scoping and types can be take two ways:

1. There is no need to have closures or similar functionality

2. There are other (presumably better) ways to achieve the same
functionality

I certainly can't comment on the second point, but an argument
for the first is where you want to call a function using say
setInterval and want to pass a lot of parameters. You can
create an "outer" function that does all the setup work and
creates any required variables, then use setInterval to call an
"internal" function that uses the variables.

The internal function has access to all the variables created in
the outer function, but you haven't needed to pass them and
their cope does not need to be global. You can keep the
internal processing tight and fast 'cos all the heavy work was
done beforehand.
 
J

Jarmo

RobG said:
Jarmo wrote:
[...]
I've yet to see a compelling need for closures in JavaScript but I'm open to
suggestion. Bring it on ;-)

Personally, I'd have preferred them to have designed variable scoping
correctly and at least provided an option for strong types then I'd have a
lot more enthusiasm for the more esoteric features.

I'm a newbie to JavaScript, but find it a fascinating language.
Your request for a compelling reason for closures and subsequent
comment on scoping and types can be take two ways:

1. There is no need to have closures or similar functionality

Right, I've not seen an argument for closures being necessary, or where the
advantages far outweigh the disadvantages. But I'm open to such an
argument. Clearly they're not strictly necessary because they're not in C
and you can do anything with C.
2. There are other (presumably better) ways to achieve the same
functionality

Depends how you define 'better' but transparency, ease of writing,
understanding, and maintenance fall high on my list. Programming is not
typically, outside of academia, a solo endeavor.
I certainly can't comment on the second point, but an argument
for the first is where you want to call a function using say
setInterval and want to pass a lot of parameters. You can
create an "outer" function that does all the setup work and
creates any required variables, then use setInterval to call an
"internal" function that uses the variables.

The internal function has access to all the variables created in
the outer function, but you haven't needed to pass them and
their cope does not need to be global. You can keep the
internal processing tight and fast 'cos all the heavy work was
done beforehand.

Right, I can see situations in which one *could* make use of closures but
none in which it's necessary, and none in which I would choose to use them.
I'll try my hardest to get a closure into my next project but I can
virtually guarantee you that it'll get kicked into touch ;-) during the peer
review process.
 
R

Richard Cornford

Jarmo said:
RobG" said:
Jarmo wrote:
[...]
I've yet to see a compelling need for closures in JavaScript
but I'm open to suggestion. Bring it on ;-)

Personally, I'd have preferred them to have designed variable
scoping correctly and at least provided an option for strong
types then I'd have a lot more enthusiasm for the more esoteric
features.

I'm a newbie to JavaScript, but find it a fascinating language.
Your request for a compelling reason for closures and
subsequent comment on scoping and types can be take two ways:

1. There is no need to have closures or similar functionality

Right, I've not seen an argument for closures being necessary,

Is necessity a suitable criteria? Under a harsh analysis very little
could be demonstrated as actually necessary. We (the human race) did,
after all, get by for the majority of its history without having
computers of any kind, so can they reasonably be considered necessary,
or just expedient?
or where the advantages far outweigh the disadvantages.

Your cited disadvantages seem to be centred around the fact that there
are many individuals writing javascript who do not understand javascript
to the extent of being able to exploit the full potential of the
language. That is certainly a reality, but should that really be taken
as grounds for the people who have made the effort to learn the language
rejecting its potential? How far is that to be taken? Do we reject OO
because it encompasses concepts that are harder to get to grips with
than those in languages that preceded it? Or refuse to program at all on
the grounds that the majority of the human population does not
understand a single line of computer code of any kind?

Obviously it is ludicrous to abandon programming because it will always
be possible to employ people who don't understand programming at all.
But it also strikes me as ludicrous to insist on crippling javascript
(by forbidding the use of its most powerful features) just because
people will apply for javascript authoring jobs without a complete
knowledge of the language. Better, in my opinion, to let them be
challenged by encountering coding techniques that they don't understand
into gaining the skills they are trying to sell.

Rather than necessity, appropriateness seems like the right criteria for
determining the approaches and techniques used in writing a computer
program. There are tasks for which OO would be over the top, and others
where it is the only sensible approach, and there are tasks where
closures are the most appropriate mechanism to employ when writing in a
language that supports them.

Maintainability is a reasonable consideration in deciding what would be
appropriate in any context, but surly that should be maintainability by
people who know the language being employed, anything else was never
very realistic from the outset. But even when code is to be employed by
less knowledgeable programmers, closures can, particularly when used for
encapsulation, significantly improve maintainability, by keeping the
internal details of reusable objects genuinely internal and leaving only
a small, simple and well documented public interface available.
But I'm open to such an argument.

Consider a fairly common task in DHTML programming; you want multiple
instances of a javascript object to be intimately associated with a
corresponding number of like DOM elements (or like structures of such
elements). Specifically, you want event handlers on DOM elements to call
method of particular object instances. The problem being that the event
handling function needs to be able to refer to the object instance, and
preferably without any interest in how that object instance if being
used by external code.

You don't need closures to do that. You can, for example, employ some
naming convention, or array-like structure in assigning object instance
references to a globally accessible property/variable and then attach
event handlers that will call a method on the appropriate stored object
instance. A reasonably self-contained and automated approach might go:-

fucntion MyObject(domElement){
this.index = MyObject.instances.length;
MyObject.instances[this.index] = this;
domElement.onclick = new Function(
'e',
'MyObject.instances['+this.index+'].doOnClick(e, this);'
);
domElement.onfocus = new Function(
'e',
'MyObject.instances['+this.index+'].doOnFocus(e, this);'
);
}

MyObject.instances = [];
MyObject.prototype.doOnClick = function(e, element){
... //function body.
}
MyObject.prototype.doOnFocus = function(e, element){
.... //function body.
}

A closure-based association of a specific method call on an object
instance with an event handler might go:-

function associateObjWithEvent(obj, mehtodName){
return (function(e){
obj[mehtodName](e, this);
});
}

function MyObject(domElement){
domElement.onclick = associateObjWithEvent(this, 'doOnClick');
domElement.onclick = associateObjWithEvent(this, 'doOnFocus');
}
MyObject.prototype.doOnClick = function(e, element){
... //function body.
}
MyObject.prototype.doOnFocus = function(e, element){
.... //function body.
}

- It is about as much code but, beyond the small performance gain, it is
simpler code and it is, in part, re-usable code. That is, the mechanism
for associating object instances with DOM element event handlers is
completely general, it can be employed by any number of 'classes'
without anything more than including simple function calls in their
constructors, and, if the closure producing function is correct in
itself, its use in those many classes will not introduce much potential
for erroneous implementation.

So that is one technique that does not use closures, but needs to be
implemented in each class that wants to use it, against a closure-based
technique that may be re-used with any 'class', and is simpler. Where
does maintainability stand on those two choices?
Clearly they're not strictly necessary
because they're not in C and you can
do anything with C.

Underneath C, and javascript, there is machine code. It is all that is
_necessary_ to program a computer (in the sense that you cannot do
without it, but can do everything that can be done with it) but
obviously it is expedient to use higher level languages of some sort.
Javascript is a higher level language than C, but C can implement
constructs that are intrinsic in javascript (in exchange for additional
authoring effort (and so can assembly language, for even more effort)).
With javascript closures are built-in and light-weight, so what is the
point in writing javascript as if it was a lower level language to
achieve the same goal?
Depends how you define 'better' but transparency, ease of
writing, understanding, and maintenance fall high on my list.

Transparent and understandable to who exactly? C programmers, Java
programmers, amateur javascript programmers, non-programmers? How many
people expect to understand javascript source code, and how many of them
are being realistic in that expectation? (Probably just the ones willing
to make the effort to study the language)

Right, I can see situations in which one *could* make use
of closures but none in which it's necessary, and none in
which I would choose to use them. I'll try my hardest
to get a closure into my next project but I can virtually
guarantee you that it'll get kicked into touch
;-) during the peer review process.

Don't 'try' to use closures, use closures where their use is
appropriate, and if you judge appropriateness correctly any peer
reviewer (qualified for the position) would have to be a fool to reject
them. And don't think in terms of necessity, there is an awful lot that
can be done without, including computer programmers.

Richard.
 
J

Jarmo

Richard Cornford said:
Don't 'try' to use closures, use closures where their use is
appropriate

Richard.

Thanks for the well-articulated response, Richard. I'll give the topic more
study.

PS when I said "try" I didn't mean that I'd manufacture a reason to use a
closure, but that I'd try to persuade the peer review board that it was an
appropriate solution in a given case. That's not a trivial task when you're
dealing with a situation in which engineers from a variety of
(non-JavaScript) backgrounds take up short-term assignments with the
technology -- you're forced, for economic reasons, to provide guidance about
what is, and what is not, acceptable use.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top