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.