Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #16117 > unrolled thread
| Started by | justaguy <lichunshen84@gmail.com> |
|---|---|
| First post | 2012-09-22 05:04 -0700 |
| Last post | 2012-09-23 15:37 -0700 |
| Articles | 17 — 5 participants |
Back to article view | Back to comp.lang.javascript
silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-22 05:04 -0700
Re: silly question on closure Stefan Weiss <krewecherl@gmail.com> - 2012-09-22 18:18 +0200
Re: silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-22 18:41 -0700
Re: silly question on closure Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-24 01:10 +0200
Closures (was: silly question on closure) Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-24 13:14 +0200
Re: silly question on closure Stefan Weiss <krewecherl@gmail.com> - 2012-09-27 05:04 +0200
Re: silly question on closure Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-27 20:50 +0200
Re: silly question on closure Stefan Weiss <krewecherl@gmail.com> - 2012-09-27 21:29 +0200
Re: silly question on closure "Tom de Neef" <tdeneef@qolor.nl> - 2012-09-22 20:00 +0200
Re: silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-22 18:42 -0700
Re: silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-23 07:31 -0700
Re: silly question on closure Stefan Weiss <krewecherl@gmail.com> - 2012-09-23 18:49 +0200
Re: silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-23 13:33 -0700
Re: silly question on closure justaguy <lichunshen84@gmail.com> - 2012-09-23 13:38 -0700
Re: silly question on closure Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-24 20:49 +0200
Re: silly question on closure Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-24 01:14 +0200
Re: silly question on closure dann90038@gmail.com - 2012-09-23 15:37 -0700
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-22 05:04 -0700 |
| Subject | silly question on closure |
| Message-ID | <a9704993-d83a-4392-8a65-82755e9ba320@u15g2000yql.googlegroups.com> |
Code:
// closure
var digit_name = function () {
var names = ['zero','one','two','three'];
return function (n) {
return names[n];
};
} ();
alert(digit_name(2));
// just a function
function digiName(n) {
var names = ['zero','one','two','three'];
alert(names[n]);
}
Question:
The closure takes so many lines while the function has only 2 lines to
get the same thing done. So, the question is, why do we use closure?
Could you elaborate a bit with a practical example?
Thanks in advance.
[toc] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2012-09-22 18:18 +0200 |
| Message-ID | <k3kocg$8ok$1@news.albasani.net> |
| In reply to | #16117 |
On 2012-09-22 14:04, justaguy wrote:
> Code:
[snipped]
> Question:
> The closure takes so many lines while the function has only 2 lines to
> get the same thing done. So, the question is, why do we use closure?
You don't, just like you don't actually use "Hello, world" in production
code. This was obviously just an example for how closures work. If this
was code intended for actual use, your "just a function" variant would
be better suited (provided it only returned the value, like in the
"closure" example).
One case where the closure variant would be preferred is if the contents
of then "names" array would take a long time to compute, or if they were
fetched from a remote source.
> Could you elaborate a bit with a practical example?
Counters are popular examples for simple closures:
var sequence = (function () {
var value = 0;
return function () {
++value;
return value;
};
})();
alert(sequence()); // 1
alert(sequence()); // 2
alert(sequence()); // 3
- stefan
[toc] | [prev] | [next] | [standalone]
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-22 18:41 -0700 |
| Message-ID | <113677ef-43a2-4b04-8be8-5a55693a54fb@a7g2000yqo.googlegroups.com> |
| In reply to | #16120 |
On Sep 22, 12:18 pm, Stefan Weiss <krewech...@gmail.com> wrote:
> On 2012-09-22 14:04, justaguy wrote:> Code:
>
> [snipped]
>
> > Question:
> > The closure takes so many lines while the function has only 2 lines to
> > get the same thing done. So, the question is, why do we use closure?
>
> You don't, just like you don't actually use "Hello, world" in production
> code. This was obviously just an example for how closures work. If this
> was code intended for actual use, your "just a function" variant would
> be better suited (provided it only returned the value, like in the
> "closure" example).
>
> One case where the closure variant would be preferred is if the contents
> of then "names" array would take a long time to compute, or if they were
> fetched from a remote source.
>
> > Could you elaborate a bit with a practical example?
>
> Counters are popular examples for simple closures:
>
> var sequence = (function () {
>
> var value = 0;
>
> return function () {
> ++value;
> return value;
> };
>
> })();
>
> alert(sequence()); // 1
> alert(sequence()); // 2
> alert(sequence()); // 3
>
> - stefan
Thank you.
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2012-09-24 01:10 +0200 |
| Message-ID | <7227299.QoKgMUOf8L@PointedEars.de> |
| In reply to | #16120 |
Stefan Weiss wrote:
> On 2012-09-22 14:04, justaguy wrote:
>> Code:
> [snipped]
>
>> Question:
>> The closure takes so many lines while the function has only 2 lines to
>> get the same thing done. So, the question is, why do we use closure?
>
> You don't, just like you don't actually use "Hello, world" in production
> code. This was obviously just an example for how closures work. If this
> was code intended for actual use, your "just a function" variant would
> be better suited (provided it only returned the value, like in the
> "closure" example).
You are mistaken as you are overlooking that creating that Array instance
and populating it with elements requires resources – memory and runtime.
Since we have only automated garbage collection, and the function may be
called a number of times, it is better to use a closure here, so that the
object would only be created, and the array only populated, once.
There is, however, a caveat to intended closures of that kind that can turn
out to be a disadvantage: The order of execution matters. All variables
used in the outer function must have the proper value *before* the outer
function is called that returns the inner function. (As the reader might
recall, I have stumbled on that myself in JSX:object.js several times.)
In a library that uses closures for optimization and did not start out with
the module pattern, this can mean that at one point the whole library must
use the module pattern, i. e. all its definitions must be enclosed in one
inner function. (I am currently in the process of refactoring JSX:object.js
like that so that I do not have to care any longer about execution order,
potentially having to sacrifice backwards-compatibility along the way.)
> One case where the closure variant would be preferred is if the contents
> of then "names" array would take a long time to compute, or if they were
> fetched from a remote source.
One, and certainly not the only or most likely case.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2012-09-24 13:14 +0200 |
| Subject | Closures (was: silly question on closure) |
| Message-ID | <3480167.NVElMTfTZn@PointedEars.de> |
| In reply to | #16135 |
Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> On 2012-09-22 14:04, justaguy wrote:
>>> Question:
>>> The closure takes so many lines while the function has only 2 lines to
>>> get the same thing done. So, the question is, why do we use closure?
>>
>> You don't, just like you don't actually use "Hello, world" in production
>> code. This was obviously just an example for how closures work. If this
>> was code intended for actual use, your "just a function" variant would
>> be better suited (provided it only returned the value, like in the
>> "closure" example).
>
> You are mistaken as you are overlooking that creating that Array instance
> and populating it with elements requires resources – memory and runtime.
> Since we have only automated garbage collection, and the function may be
> called a number of times, it is better to use a closure here, so that the
> object would only be created, and the array only populated, once.
>
> There is, however, a caveat to intended closures of that kind that can
> turn out to be a disadvantage: The order of execution matters. All
> variables used in the outer function must have the proper value *before*
> the outer function is called that returns the inner function. (As the
> reader might recall, I have stumbled on that myself in JSX:object.js
> several times.)
>
> In a library that uses closures for optimization and did not start out
> with the module pattern, this can mean that at one point the whole library
> must use the module pattern, i. e. all its definitions must be enclosed in
> one inner function. (I am currently in the process of refactoring
> JSX:object.js like that so that I do not have to care any longer about
> execution order, potentially having to sacrifice backwards-compatibility
> along the way.)
And if the library has optional dependencies, this can mean that if you are
using the module pattern, explicit initialization of the bound variable must
be moved to the inner function (as Douglas Crockford has showed once in a
very interesting presentation¹ on closures [1]):
(function () {
var dep;
return function () {
/*
* or !dep && …;
* depends on the initial and future value, code style,
* and other factors
*/
if (typeof dep == "undefined"
&& typeof optional != "undefined" && optional)
{
dep = optional.dependency.available.now;
}
if (typeof dep != "undefined")
{
/* do fancy things using `dep' */
}
else
{
/* do not so fancy things, without `dep' */
}
};
}());
For a real-world example, in several JSX methods I am using features defined
in other parts of JSX that are intentionally optional (like several other
well-designed libraries, JSX is modular). If I would initialize the outer
local variable with the corresponding property (because I want to avoid the
slower looking-up of the property down the scope chain and prototype chains
starting with the Global Object every time the method is called), then that
*optional* feature would become *mandatory*: the initializing code would not
run without it. Or if it would run, the initialization value might turn out
to be `undefined' because the formerly optional part was not loaded yet,
leading to a runtime error when the returned function is called, which is
even worse.
This way, the initilization may still fail when the returned function is
called, but at least I can debug that easily, and it will show up in unit
test results. The other way, the unit test of the optional feature would
not be possible as the whole library could not be tested without it.
An additional advantage of this approach at initialization with references
to *new* objects is that not only is the object only created once if the
function is called; it is not created *at all* if the function is *never*
called. So a lot of memory can be saved without losing flexibility and
versatility. Which is a Good Thing.
(It turns out again that there are no silly questions, only questions asked
the silly way.)
PointedEars
______
¹ You do not have to agree with all that he says (I certainly do not)
to appreciate parts of it.
[1]
<http://www.youtube.com/watch?feature=player_detailpage&v=ya4UHuXNygM#t=1595s>
--
Sometimes, what you learn is wrong. If those wrong ideas are close to the
root of the knowledge tree you build on a particular subject, pruning the
bad branches can sometimes cause the whole tree to collapse.
-- Mike Duffy in cljs, <news:Xns9FB6521286DB8invalidcom@94.75.214.39>
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2012-09-27 05:04 +0200 |
| Message-ID | <k40fod$k2d$1@news.albasani.net> |
| In reply to | #16135 |
On 2012-09-24 01:10, Thomas 'PointedEars' Lahn wrote: > Stefan Weiss wrote: >> On 2012-09-22 14:04, justaguy wrote: >>> The closure takes so many lines while the function has only 2 lines to >>> get the same thing done. So, the question is, why do we use closure? >> >> You don't, just like you don't actually use "Hello, world" in production >> code. This was obviously just an example for how closures work. If this >> was code intended for actual use, your "just a function" variant would >> be better suited (provided it only returned the value, like in the >> "closure" example). > > You are mistaken as you are overlooking that creating that Array instance > and populating it with elements requires resources – memory and runtime. > Since we have only automated garbage collection, and the function may be > called a number of times, it is better to use a closure here, so that the > object would only be created, and the array only populated, once. I would say that depends on the use case. I have no doubt that closures can offer performance benefits even with a simple 4-element array like this, but unless you're running the function a million times in a tight loop, the difference will be hardly noticable. There's a often a tradeoff between legibility and performance. Introducing temporary variables, helper functions, layers of indirection, etc, can all hurt performance, but we still do it because it helps us keep our code clean, understandable, and maintainable. In the vast majority of cases, JS performance is not a problem (anymore). In this particular case, the goal was "understanding closures". It's a fair assumption to make that the code was not running in a tight loop, and that the OP was not overly troubled by the performance of his script. You're writing a general purpose library, the OP is learning JS. Your goals are different. Recommending the closure style whenever possible, regardless of circumstances, smacks of premature optimization. - stefan
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2012-09-27 20:50 +0200 |
| Message-ID | <3738235.beI7O1F77D@PointedEars.de> |
| In reply to | #16172 |
Stefan Weiss wrote:
> On 2012-09-24 01:10, Thomas 'PointedEars' Lahn wrote:
>> Stefan Weiss wrote:
>>> On 2012-09-22 14:04, justaguy wrote:
>>>> The closure takes so many lines while the function has only 2 lines to
>>>> get the same thing done. So, the question is, why do we use closure?
>>>
>>> You don't, just like you don't actually use "Hello, world" in production
>>> code. This was obviously just an example for how closures work. If this
>>> was code intended for actual use, your "just a function" variant would
>>> be better suited (provided it only returned the value, like in the
>>> "closure" example).
>>
>> You are mistaken as you are overlooking that creating that Array instance
>> and populating it with elements requires resources – memory and runtime.
>> Since we have only automated garbage collection, and the function may be
>> called a number of times, it is better to use a closure here, so that the
>> object would only be created, and the array only populated, once.
>
> I would say that depends on the use case.
Of course it does.
> I have no doubt that closures can offer performance benefits even with a
> simple 4-element array like this, but unless you're running the function a
> million times in a tight loop, the difference will be hardly noticable.
Of course. You are missing the point.
> There's a often a tradeoff between legibility and performance.
> Introducing temporary variables, helper functions, layers of
> indirection, etc, can all hurt performance, but we still do it because
> it helps us keep our code clean, understandable, and maintainable.
False dichotomy.
> In the vast majority of cases, JS performance is not a problem
> (anymore).
You are very much mistaken.
> In this particular case, the goal was "understanding closures". It's a
> fair assumption to make that the code was not running in a tight loop, and
> that the OP was not overly troubled by the performance of his script.
I have disputed your assertion that closures are to be avoided with a two-
line function because they would not be worth it in any case.
> You're writing a general purpose library, the OP is learning JS. Your
> goals are different. Recommending the closure style whenever possible,
> regardless of circumstances, smacks of premature optimization.
Which is why I am not doing that.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2012-09-27 21:29 +0200 |
| Message-ID | <k429e2$1rj$1@news.albasani.net> |
| In reply to | #16200 |
On 2012-09-27 20:50, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> In the vast majority of cases, JS performance is not a problem
>> (anymore).
>
> You are very much mistaken.
So you actually believe that, today, JS performance is a problem in the
_vast_ _majority_ of cases? That's funny.
> I have disputed your assertion that closures are to be avoided with a two-
> line function because they would not be worth it in any case.
I'm not surprised that you found something to dispute; seems to be a
hobby of yours. Next time, maybe dispute something I actually said?
When I wrote that the non-closure variant would be better suited, I was
not talking about "in any case", I was referring to one specific
example. Here's that function again:
function digiName (n) {
var names = ['zero','one','two','three'];
return names[n]; // fixed from alert()
}
This is obviously from an exercise, and not from performance critical
production code. Do we really need a closure here? And assuming this
function is not called thousands of times in a loop (a fair assumption
for this type of training exercise), would you really prefer a closure?
If you do, then that's nice for you, but it's a matter of personal
preference, at best. The result would be harder to read, take up more
space, and the difference in performance would be hardly measurable.
But dispute away, if it makes you happy.
- stefan
[toc] | [prev] | [next] | [standalone]
| From | "Tom de Neef" <tdeneef@qolor.nl> |
|---|---|
| Date | 2012-09-22 20:00 +0200 |
| Message-ID | <505dfcdb$0$6848$e4fe514c@news2.news.xs4all.nl> |
| In reply to | #16117 |
"justaguy" <lichunshen84@gmail.com> wrote > Question: > The closure takes so many lines while the function has only 2 lines to > get the same thing done. So, the question is, why do we use closure? > Could you elaborate a bit with a practical example? > Suppose you need a global variable to keep track of something (like an element that is being moved by cursor movements). Your script file would contain a line like var currentElement; near the top and you can freely reference this variable in all your functions. Now you attach another .js file, such as a library written by someone else. That library may also contain a global 'currentElement'. Typically, you will want a coding mechanism to avoid a clash that may result from this doublure. With a closure you can hide variables and restrict their access to predefined uses. The example of the counter, provided by Stefan, is such a case. Tom
[toc] | [prev] | [next] | [standalone]
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-22 18:42 -0700 |
| Message-ID | <02f07c90-fde4-4cc6-b44b-95239771c06d@m9g2000yqi.googlegroups.com> |
| In reply to | #16122 |
On Sep 22, 2:01 pm, "Tom de Neef" <tden...@qolor.nl> wrote: > "justaguy" <lichunshe...@gmail.com> wrote > > > Question: > > The closure takes so many lines while the function has only 2 lines to > > get the same thing done. So, the question is, why do we use closure? > > Could you elaborate a bit with a practical example? > > Suppose you need a global variable to keep track of something (like an > element that is being moved by cursor movements). > Your script file would contain a line like > var currentElement; > near the top and you can freely reference this variable in all your > functions. > Now you attach another .js file, such as a library written by someone else. > That library may also contain a global 'currentElement'. Typically, you will > want a coding mechanism to avoid a clash that may result from this doublure. > With a closure you can hide variables and restrict their access to > predefined uses. The example of the counter, provided by Stefan, is such a > case. > Tom Thank you. So, we should avoid Global variable when we can or naming it "strangely" to avoid collision with libraries, fair assumption?
[toc] | [prev] | [next] | [standalone]
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-23 07:31 -0700 |
| Message-ID | <7008a319-a3c7-43b4-9a05-dd1db287472f@l14g2000yqo.googlegroups.com> |
| In reply to | #16127 |
On Sep 22, 9:42 pm, justaguy <lichunshe...@gmail.com> wrote: > On Sep 22, 2:01 pm, "Tom de Neef" <tden...@qolor.nl> wrote: > > > > > > > > > > > "justaguy" <lichunshe...@gmail.com> wrote > > > > Question: > > > The closure takes so many lines while the function has only 2 lines to > > > get the same thing done. So, the question is, why do we use closure? > > > Could you elaborate a bit with a practical example? > > > Suppose you need a global variable to keep track of something (like an > > element that is being moved by cursor movements). > > Your script file would contain a line like > > var currentElement; > > near the top and you can freely reference this variable in all your > > functions. > > Now you attach another .js file, such as a library written by someone else. > > That library may also contain a global 'currentElement'. Typically, you will > > want a coding mechanism to avoid a clash that may result from this doublure. > > With a closure you can hide variables and restrict their access to > > predefined uses. The example of the counter, provided by Stefan, is such a > > case. > > Tom > > Thank you. So, we should avoid Global variable when we can or naming > it "strangely" to avoid collision with libraries, fair assumption? Ok, I've implemented closure with my app, and now I see its beauty, in the meantime, I don't know why ++value; would increment by 2. I attempted with +value to no avail Thanks.
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2012-09-23 18:49 +0200 |
| Message-ID | <k3nejp$6v3$1@news.albasani.net> |
| In reply to | #16128 |
On 2012-09-23 16:31, justaguy wrote: > Ok, I've implemented closure with my app, and now I see its beauty, in > the meantime, I don't know why > ++value; > would increment by 2. > I attempted with > +value to no avail The ++ operator increments by 1, not 2. The unary + operator does not increment at all. This is basic syntax. I think you would profit enormously from reading this guide: https://developer.mozilla.org/en-US/docs/JavaScript/Guide Chapter 5 is about expressions and operators, chapter 14 is about closures. - stefan
[toc] | [prev] | [next] | [standalone]
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-23 13:33 -0700 |
| Message-ID | <ba270ed3-6eb4-436a-9713-a9d9fb2be88f@h4g2000yqo.googlegroups.com> |
| In reply to | #16129 |
On Sep 23, 12:50 pm, Stefan Weiss <krewech...@gmail.com> wrote:
> On 2012-09-23 16:31, justaguy wrote:
>
> > Ok, I've implemented closure with my app, and now I see its beauty, in
> > the meantime, I don't know why
> > ++value;
> > would increment by 2.
> > I attempted with
> > +value to no avail
>
> The ++ operator increments by 1, not 2.
> The unary + operator does not increment at all.
>
> This is basic syntax. I think you would profit enormously from reading
> this guide:
>
> https://developer.mozilla.org/en-US/docs/JavaScript/Guide
>
> Chapter 5 is about expressions and operators, chapter 14 is about closures.
>
> - stefan
Very interesting, thank you.
The section about Object Literal has sample code similar to the
following:
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
// the following would fail, err msg: manyCars is not defined
// is that because an object property can be called with array
notation of []
// if the property has simple value such as property of 7 with
value of "Mazda"?
console.log(car[manyCars]); // a: "Saab", "b": "Jeep"
Many thanks.
[toc] | [prev] | [next] | [standalone]
| From | justaguy <lichunshen84@gmail.com> |
|---|---|
| Date | 2012-09-23 13:38 -0700 |
| Message-ID | <0c5aab04-4fe4-41f8-b50f-ec9ea4821905@e18g2000yqo.googlegroups.com> |
| In reply to | #16129 |
On Sep 23, 12:50 pm, Stefan Weiss <krewech...@gmail.com> wrote: > On 2012-09-23 16:31, justaguy wrote: > > > Ok, I've implemented closure with my app, and now I see its beauty, in > > the meantime, I don't know why > > ++value; > > would increment by 2. > > I attempted with > > +value to no avail > > The ++ operator increments by 1, not 2. > The unary + operator does not increment at all. > > This is basic syntax. I think you would profit enormously from reading > this guide: > > https://developer.mozilla.org/en-US/docs/JavaScript/Guide > > Chapter 5 is about expressions and operators, chapter 14 is about closures. > > - stefan Ok, back the my latest question/post, I guess I was almost correct, manyCars are considered an object-like property, and it needs the " like the following, console.log(car["manyCars"]); // a: "Saab", "b": "Jeep" Thanks.
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2012-09-24 20:49 +0200 |
| Message-ID | <1779068.4r8zmURcku@PointedEars.de> |
| In reply to | #16131 |
justaguy wrote: > On Sep 23, 12:50 pm, Stefan Weiss <krewech...@gmail.com> wrote: >> On 2012-09-23 16:31, justaguy wrote: >> > Ok, I've implemented closure with my app, and now I see its beauty, in >> > the meantime, I don't know why >> > ++value; >> > would increment by 2. >> > I attempted with >> > +value to no avail >> >> The ++ operator increments by 1, not 2. >> The unary + operator does not increment at all. >> >> This is basic syntax. I think you would profit enormously from reading >> this guide: >> >> https://developer.mozilla.org/en-US/docs/JavaScript/Guide >> >> Chapter 5 is about expressions and operators, chapter 14 is about >> closures. > > Ok, back the my latest question/post, I guess I was almost correct, > manyCars are considered an object-like property, and it needs the " > like the following, > console.log(car["manyCars"]); // a: "Saab", "b": "Jeep" You are not making any sense. There are no "object-like properties" (there can be *array*-like *objects*, a completely different thing); these languages are loosely typed. Getters, setters and freezing (ES5) aside, any property can assume any value at any time. And a property's *value* is irrelevant to the *syntax* the property can be accessed with¹: console.log(car.manyCars); works as well, of course. The only case where the bracket accessor notation is required is when the property name is not an identifier, including when it is a reserved word.¹ (Whereas the latter has been fixed with ES 5, so one can hope that some day – perhaps 10 years from now – non-ES-5-conforming engines have gone.) What does not work well if `manyCars' is a reference to an object, is console.log(car[manyCars]); because property names are string values, so the value of `manyCars' would be converted to a string value there if it is not already is one. And for object references that means the toString() method of the object is called, which for built-in objects returns just "[object Object]". And there is no property with *that* name in your program. (JSX:map.js allows you to use objects as keys, refining the concept underlying jshashtable by Tim Down.) If you want to have any hope of understanding these languages (yes, it is not only one) some day, you should read a lot more carefully because I doubt anything in the JavaScript Guide suggests what you stated here. And you should stop posting via Google Groups using a pseudonym, because the people you want to be corrected by do not have the time to filter out your posting from all the other junk that is usually posted via Google Groups and by pseudonymous posters to Usenet. I am making an exception for this posting, of course. PointedEars ___________ ¹ And by convention and for clarity of code, it is useful when accessing DOM collections with ECMAScript implementations. -- Danny Goodman's books are out of date and teach practices that are positively harmful for cross-browser scripting. -- Richard Cornford, cljs, <cife6q$253$1$8300dec7@news.demon.co.uk> (2004)
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2012-09-24 01:14 +0200 |
| Message-ID | <8042824.8LXobfXzMX@PointedEars.de> |
| In reply to | #16122 |
Tom de Neef wrote:
> […] With a closure you can hide variables and restrict their access to
> predefined uses. The example of the counter, provided by Stefan, is such a
> case.
However, one should be aware that in addition to arbitrary execution order
one is also sacrificing thread-safety this way the same as if the local
variable was global: All calls to the returned function will use the same
local variable of the returning outer function.
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
[toc] | [prev] | [next] | [standalone]
| From | dann90038@gmail.com |
|---|---|
| Date | 2012-09-23 15:37 -0700 |
| Message-ID | <947392c4-a7da-4335-81cf-58317a8cbeda@googlegroups.com> |
| In reply to | #16117 |
just a note on debugging with firebug using console.log(), it allows \n in the string section and positional parameters %s, eg:
console.log('many cars here -> %s\n Saab -> %s\n Mazda -> %s', car.manyCars, car.manyCars.a, car[7])
if interested on a bit more -> http://michaelsync.net/category/firebug/page/2
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.javascript
csiph-web