By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,732 Members | 1,435 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,732 IT Pros & Developers. It's quick & easy.

jslint doesn't like my syntax for conditional object creation

P: n/a
Hi,

I have been using the following line of code to create an object called
"Serious" if it doesn't already exist.

if (Serious == null) {var Serious = {};}

This works in the scripts I use it but but www.jslint.com is not happy
with me.

Problem at line 1 character 16: Use '===' to compare with 'null'.
if (Serious == null) {var Serious = {};}

Problem at line 1 character 27: Var Serious was used before it
was declared.
if (Serious == null) {var Serious = {};}

Problem at line 1 character 27: Identifier 'Serious' already
declared as global
if (Serious == null) {var Serious = {};}

If I change to "===" then the condition is never true.

What is the correct way to create an empty object only if the object
does not exist?

Thanks,
Peter

May 22 '06 #1
Share this Question
Share on Google+
44 Replies


P: n/a
pe**********@gmail.com wrote:
I have been using the following line of code to create
an object called "Serious" if it doesn't already exist.

if (Serious == null) {var Serious = {};}

This works in the scripts I use it but but www.jslint.com is
not happy with me.

Problem at line 1 character 16: Use '===' to compare with
'null'. if (Serious == null) {var Serious = {};}
The double equals comparison is type-converting, and equates Undefined
with Null. JSLint seems to take the stance that if you are going to
compare something with null then you should only be interested in
whether it is null or not, and so should use a comparison that telly you
precisely that.
Problem at line 1 character 27: Var Serious was used
before it was declared.
if (Serious == null) {var Serious = {};}
As the units of scoping are function bodies any variable declared within
a function body is visible to the function's entire contents, and
variable declarations anywhere within a function's immediate contents
(rather than nested functions) result in the creation of a named
property of the Variable object _prior_ to the execution of any function
body code.

This mans that:-

if (Serious == null) {var Serious = {};}

- is no different in its behaviour from:-

var Serious;
if (Serious == null) {Serious = {};}

- and given that (and particularly the fact that all declared variable
result in the creation of Variable object properties prior to function
body code execution) it is often felt that all function local variable
declarations should appear at the top of a function body's code.
Problem at line 1 character 27: Identifier 'Serious'
already declared as global
if (Serious == null) {var Serious = {};}
Declaring a function local variable will mask global variables so that
they cannot be accessed within the function body. However, this is
unlikely to be necessary or desirable, so it may be felt that if a
variable is declared globally any use of the same variable name for a
local variable should be flagged as a potential error.
If I change to "===" then the condition is never true.
No, the unassigned local variable will have the Undefined value so while
type-converting comparison will equate null with undefined strict
comparison will not.
What is the correct way to create an empty object only if
the object does not exist?


There is not really any 'correct' test, except the test that tells you
precisely what you want to know, which depends upon what you want to
know.

If the only possibilities for a declared global variable are the
undefined value or a reference to an object (and nothing else) then a
type-converting (to boolean) test will be false for the former and true
for the latter:-

if(Serious){
... //Serious is not undefined (therefor is an object reference)
}

- or:-

if(!Serious){
... //Serious is undefined (therefor is not an object reference)
}

Less efficient tests such as using - typeof - can be more
discriminating:-

if(typeof Serious == 'undefined'){
... //Serious is undefined.
}

- which can have advantages if the possibilities are less well defined.

Richard.
May 22 '06 #2

P: n/a
VK

pe**********@gmail.com wrote:
I have been using the following line of code to create an object called
"Serious" if it doesn't already exist.

if (Serious == null) {var Serious = {};}

This works in the scripts I use it but but www.jslint.com is not happy
with me.

Problem at line 1 character 16: Use '===' to compare with 'null'.
if (Serious == null) {var Serious = {};}


JSLint is right what your code is wrong, but in this case it barks up
the wrong tree. You can not address a non-initialized variable unless
in try-catch block or in typeof operator.

if (Serious == null)
in order to check this statement the engine needs to calculate the
value of Serious. If Serious doesn'r exists, we are getting an attempt
to access non-initialized variable and that is the end of the story.
Try this to see it in action:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>$Template$</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
try {
if (Serious == null) { Serious = {}; }
}
catch(e) {
alert(e.message);
// error "Serious is not defined"
}
</script>
</head>
<body>
<p>No content</p>
</body>
</html>
The proper variant (with some respect to the common programming
practice) is:

if (typeof Serious == "undefined") {var Serious = {};}

or (reversed style a la Visual Studio)

if ("undefined" == typeof Serious) {var Serious = {};}

May 23 '06 #3

P: n/a
VK wrote:
pe**********@gmail.com wrote:
I have been using the following line of code to create an object
called "Serious" if it doesn't already exist.

if (Serious == null) {var Serious = {};}

This works in the scripts I use it but but www.jslint.com is not
happy with me.

Problem at line 1 character 16: Use '===' to compare with 'null'.
if (Serious == null) {var Serious = {};}
JSLint is right what your code is wrong, but in this case it barks up
the wrong tree.


How would you know?
You can not address a non-initialized variable unless
in try-catch block or in typeof operator.
Bullshit. Trying to read the value a non-declared Identifier will
produce an error (unless it is the operand of the - typeof - operator)
but the Identifier in question clearly is declared (with the - var -
keyword locally and given "Problem at line 1 character 27: Identifier
'Serious' already declared as global" in the JSLint output, the same
Identifier must already be declared globally as well.
if (Serious == null)
in order to check this statement the engine needs to calculate the
value of Serious.
And that value is the undefined value (the single value of the
Undefined type).
If Serious doesn'r exists, we are getting an attempt
to access non-initialized variable and that is the end of the story. <snip>

A declared variable is implicitly initialized to Undefined during
variable instantiation.
The proper variant
How would you know?
(with some respect to the common programming
practice)
How would you know?
is:

if (typeof Serious == "undefined") {var Serious = {};}

<snip>

As the variable declaration is retained here (while it was omitted from
you example of error-producing code) you supposed 'issue' does not
apply, and the appropriate type of test varies with the context of the
code. However, 'common programming practice' would not declare a
variable in that context in javascript.

Richard.

May 23 '06 #4

P: n/a
VK

Richard Cornford wrote:
if (Serious == null) {var Serious = {};}
JSLint is right what your code is wrong, but in this case it barks up
the wrong tree.


How would you know?


And how would you?
That was a wrong question from OP in the first place, and I should skip
on it instead of "reading" imaginary code around. That should be full /
minimum working code posted, and /then/ the relevant error description.
Trying to read the value a non-declared Identifier will
produce an error (unless it is the operand of the - typeof - operator)
but the Identifier in question clearly is declared (with the - var -
keyword locally and given "Problem at line 1 character 27: Identifier
'Serious' already declared as global" in the JSLint output, the same
Identifier must already be declared globally as well.


Unless the block in question is inside function so a function level
variable with the same name is created depending on the global variable
existence. Or unless... briefly do not repeat my mistake and don't try
to restore 3rd party context by few errors. Wait until OP will post the
relevant code.

May 23 '06 #5

P: n/a
VK wrote:
Richard Cornford wrote:
if (Serious == null) {var Serious = {};}

JSLint is right what your code is wrong, but in this case it barks up
the wrong tree.
How would you know?


And how would you?


That is a silly question. I know because I have spent some time
learning Javascript. I have also read and understood the source code
for JSLint and discussed the motivation for its error and warning
output with its author.
That was a wrong question from OP in the first place, and I should
skip on it instead of "reading" imaginary code around. That should
be full / minimum working code posted, and /then/ the relevant error
description.
If there was not enough information to answer the question why did you
attempt to answer it instead of asking for the additional information?
But the question asked was sufficient as it provided the code that
JSLint was complaining about and sufficient of JSLint's output to fill
in the only missing code (the global declaration of the variable).
Trying to read the value a non-declared Identifier will
produce an error (unless it is the operand of the - typeof - operator)
but the Identifier in question clearly is declared (with the - var -
keyword locally and given "Problem at line 1 character 27: Identifier
'Serious' already declared as global" in the JSLint output, the same
Identifier must already be declared globally as well).


Unless


No, not "unless", the variable _was_ declared. We can see the - var -
keyword in the code.
the block in question is inside function so a function level
variable with the same name is created depending on the global
variable existence.
"Depending on the global variable existence"? There is no such thing as
a conditional variable declaration in javascript. Any occurrence of the
- var - keyword followed by an Identifier declares a variable with a
name corresponding with the Identifier in the pertinent execution
context. A variable is created for each Identifier used with - var -,
unconditionally.

This is a basic fact about the javascript language. I have no
expectation that you would know these things but I wish you would stop
making out that you know anything about javascript (or that you have
anything to teach anyone) while not understanding the basics of the
language.
Or unless... briefly do not repeat my mistake and don't try
to restore 3rd party context by few errors. Wait until OP will post the
relevant code.


As if I would take your advice on anything.

Richard.

May 23 '06 #6

P: n/a
VK
VK wrote:
Or unless... briefly do not repeat my mistake and don't try
to restore 3rd party context by few errors. Wait until OP will post the
relevant code.

Richard Cornford wrote: As if I would take your advice on anything.
And that's a shame because whoever doesn't take VK's advises is being
beat down publically (smile, joke, humor :-)

Go to <http://www.jslint.com/> and paste this single line of text to
validate:
if (Serious == null) {var Serious = {};}

You get these exact errors OP got:
Problem at line 1 character 16: Use '===' to compare with 'null'.

if (Serious == null) {var Serious = {};}

Problem at line 1 character 27: Var Serious was used before it was
declared.

if (Serious == null) {var Serious = {};}

Problem at line 1 character 27: Identifier 'Serious' already
declared as global

if (Serious == null) {var Serious = {};}

As I mentioned before, no one of them actually points to the real
problem (exception raised by addressing non-declared variable). JSLint
neuristic needs much more improvement on that.
The code you "restored" in your mind gives all different errors:
var Serious;
if (Serious == null) {var Serious = {};}

gives:

Problem at line 2 character 16: Use '===' to compare with 'null'.

if (Serious == null) {var Serious = {};}

Problem at line 2 character 27: Identifier 'Serious' already declared
as var*

if (Serious == null) {var Serious = {};}

That is a silly question. I know because I have spent some time
learning Javascript. I have also read and understood the source code
for JSLint and discussed the motivation for its error and warning
output with its author.
You may want to have more discussion with him after that (just don't
use the bat :-)

There is no such thing as a conditional variable declaration in javascript.


Eh?? No comments, really.

May 23 '06 #7

P: n/a
VK wrote:
VK wrote:
Or unless... briefly do not repeat my mistake and don't try
to restore 3rd party context by few errors. Wait until OP will post the
relevant code.
Richard Cornford wrote:
As if I would take your advice on anything.

You have quoted the above out of context and re-ordered. That is
disingenuous at minimum.
And that's a shame because whoever doesn't take VK's advises
is being beat down publically (smile, joke, humor :-)
On the contrary, disregarding anything you say will generally save
everyone a great deal of time.
Go to <http://www.jslint.com/> and paste this single line of text to
validate:
if (Serious == null) {var Serious = {};} <snip> As I mentioned before, no one of them actually points to the real
problem
I take it you don't grasp the concept of lint programs.
(exception raised by addressing non-declared variable).
How many times? There is no non-declared variable. We can see the - var
- keyword being used to declare it.
JSLint
neuristic needs much more improvement on that.
JSLint does exactly what it was designed to do.
The code you "restored" in your mind gives all different errors:
var Serious;
if (Serious == null) {var Serious = {};}


What makes you think that nonsense was in my mind?

<snip> There is no such thing as a conditional variable declaration in javascript.


Eh?? No comments, really.


There would be no point in your commenting as that is a statement of a
basic truth in javascript. As you have never really understood local
variables as a concept I would not be surprised if you did not believe
me, but that makes no difference to reality.

Richard.

May 23 '06 #8

P: n/a
VK

Richard Cornford wrote:
VK wrote:
(exception raised by addressing non-declared variable).
How many times? There is no non-declared variable. We can see the - var
- keyword being used to declare it.


Richard, are you trying to be stubbering up to the point to be silly?

if (Serious == null) {var Serious = {};}

In order to decide execute if-block or not, the program has to obtain
first the boolean value of the condition check (Serious == null)

In order to obtain boolean value of (Serious == null) the program has
to retrieve the value of Serious.

In order to retrieve the value of serious it has to address this
variable. If variable is not declared, it raise "Undefined indentifier"
error (error #5009 by JScript notation).

As this error raised outside of try-catch block we get uncaught error
and execution stops right there.

The execution never gets to the content of {...} so it is irrelevant
whether you have "var" there or not.
JSLint does exactly what it was designed to do.


You mean restoring the entire program out of a single line?
The code you "restored" in your mind gives all different errors:
var Serious;
if (Serious == null) {var Serious = {};}


What makes you think that nonsense was in my mind?


Because all your previous assumptions were made on that somewhere
before that line there is something like
var Serious;

If you though (like me) that Serious was never mentioned in the OP's
code before the line
if (Serious == null) {var Serious = {};}

then why did you start to argue with me?

May 23 '06 #9

P: n/a
VK wrote:
Richard Cornford wrote:
VK wrote:
(exception raised by addressing non-declared variable).
How many times? There is no non-declared variable. We can see the - var
- keyword being used to declare it.


Richard, are you trying to be stubbering up to the point to be silly?


Silly? I am being factually accurate; the variable is declared and we
can see that it is being declared (we, in this case, referring to
people who understand javascript, not you).
if (Serious == null) {var Serious = {};}

In order to decide execute if-block or not, the program has to obtain
first the boolean value of the condition check (Serious == null)
It does.
In order to obtain boolean value of (Serious == null) the program
has to retrieve the value of Serious.
And Serious has the undefined value (assuming that there is no
assignment to Serious prior to that point).
In order to retrieve the value of serious it has to address this
variable. If variable is not declared, it raise "Undefined indentifier"
error (error #5009 by JScript notation).
It would if Serious had not been declared, but it has so that is not an
issue.
As this error raised outside of try-catch block we get uncaught error
and execution stops right there.
Not in this case a Serious has been declared. I wonder how many times
it will be necessary for me to say this. I realise that much what I say
goes right over your head but it makes it even more obvious than is
usual from your posts that you are a fool when you do not see my being
adamant on this point as grounds for suspecting that you are wrong. But
your absolute confidence that you are never in error in what you
mistake for your understanding of javascript, is easily the biggest
barrier in your ever acquiring an understanding of javascript.
The execution never gets to the content of {...} so it is irrelevant
whether you have "var" there or not.
It is the fact that this is not true that makes conditional variable
declarations impossible in javascript. VariableDeclaration productions
are processed during 'variable instantiation' (ECMA 262, 3rd ed.
Section 10.1.3) to create properties of the Variable object, prior to
the execution of code for the execution context. So the creation of
such properties of the Variable object cannot be influenced by control
flow inside the code as it has not been executed at the point of
'variable instantiation'.

Each and every pertinent Variable Declaration is examined during
variable instantiation and for each Identifier used a property of the
Variable object is created, regardless of the context in the code where
the - var Identifier - occurs.
JSLint does exactly what it was designed to do.


You mean restoring the entire program out of a single line?


No, I mean what I wrote.
The code you "restored" in your mind gives all different errors:
var Serious;
if (Serious == null) {var Serious = {};}


What makes you think that nonsense was in my mind?


Because all your previous assumptions were made on that
somewhere before that line there is something like
var Serious;


No they were not. Your thinking that I must have assumed that is a
product of your not understanding variable declarations in Javascript.
If you though (like me) that Serious was never mentioned in the OP's
code before the line
if (Serious == null) {var Serious = {};}

then why did you start to argue with me?


Because you posted a sequence of nonsense and untrue statements about
javascript based on your (very) personal misconceptions of the
language, as usual.

Richard.

May 23 '06 #10

P: n/a
VK
Richard Cornford wrote:
VariableDeclaration productions
are processed during 'variable instantiation' (ECMA 262, 3rd ed.
Section 10.1.3) to create properties of the Variable object, prior to
the execution of code for the execution context. So the creation of
such properties of the Variable object cannot be influenced by control
flow inside the code as it has not been executed at the point of
'variable instantiation'.


OK, I admit you got me on this one - I was wrong (and ECMA specs amused
me once again).

For me the "variable declaration" is strictly like:

var a = null;
var b = '';
var ...
....
// program flow
....

and that was the point I was arguing (that the variable Serious was not
explicetly pre-declared). It did not cross my mind of this hack with
the parser fetching all var operators and pre-declaring them.

So presuming that
if (Serious == null) { var Serious = {}; }

is used outside of any function, this trick does work and it doesn't
lead to the exception. (Within a function such check is useless as
local Serious will be always here with value undefined).

I guess we can adjust the mutual score (your var operator pre-fetching
against my script tag usage :-)

But why did you decide to account this trick in the JSLint? I thought
it was supposed to be a code validator and cleaner, not a curiosity
store? Why did you decide to teach your users that if they are smart
and careful enough, they can avoid pre-declaring variables in their
code?

May 23 '06 #11

P: n/a
VK wrote:
Richard Cornford wrote:
VariableDeclaration productions
are processed during 'variable instantiation' (ECMA 262, 3rd ed.
Section 10.1.3) to create properties of the Variable object, prior to
the execution of code for the execution context. So the creation of
such properties of the Variable object cannot be influenced by control
flow inside the code as it has not been executed at the point of
'variable instantiation'.
OK, I admit you got me on this one


I have "got" you on every point I have ever made in your direction, you
are just not rational enough to comprehend that.
- I was wrong ... <snip>

And look how much time and effort was required to convince you of just
one basic truth about javascript. This is why the nonsense you post is
doubly harmful, not only is it rubbish itself but the time and effort
needed to correct you (often wasted due to your recalcitrance) is
denied to the more deserving.

<snip> .. It did not cross my mind of this hack with
the parser fetching all var operators and pre-declaring them.
I don't need to hear your latest excuse for posting nonsense. Just for
once take the advice you are given and go and learn the basics of
javascript _before_ trying to give advice to others on the subject.

<snip> I guess we can adjust the mutual score (your var operator
pre-fetching against my script tag usage :-)
No 'score' is necessary. You are a probably insane halfwit who has
never even grasped the basics of javascript but is so deluded that you
mistake the content of your mind for something worthwhile and in some
way related to the subject. Nobody in their right mind would pay any
hee to anything you had to say on any subject at all, and that will
inevitably include me.
But why did you decide to account this trick in the JSLint?
Are you asking me questions in the role of author of JSLint? I am not
its author.
I thought it was supposed to be a code validator and cleaner,
not a curiosity store?
I didn't think that you had grasped the role of lint programs. I won't
attempt to explain because it would go right over your head anyway.
Why did you decide to teach your users
My users?
that if they are smart and careful enough, they can avoid
pre-declaring variables in their code?


What are you talking about now?

Richard.

May 23 '06 #12

P: n/a
VK
VK wrote:
I thought it was supposed to be a code validator and cleaner,
not a curiosity store? <snip> that if they are smart and careful enough, they can avoid
pre-declaring variables in their code?


Richard Cornford wrote: What are you talking about now?


I am not an angel but you are the most stubbering horns into wall
person I've seen so far.

All the thread through you were saying that the line like
var Serious; // pre-declare for future use
did not existed and doesn't have to exist in the original program.

You whole point was build on the statement that the first time the
character sequence "var Serious" occured in the source code, it was in
the line passed through the JSLint:
if (Serious == null) {var Serious = {};}

You were stating that ECMA specs are covering this case (unfortunately
they are) and that the fact that the character sequence "var Serious"
is contained in the source code in any place is good enough to have
Serious as undefined (rather than to get an exception on trying to use
it).

Fine. Right.

Do you really state that /this/ is an Ok interpretation of the term
"pre-declare variable in your programs"?

<http://www.jslint.com/lint.html>
<q>
JavaScript allows var definitions to occur anywhere within a function.
JSLint is more strict.
JSLint expects that a var will be declared only once, and that it will
be declared before it is used.
</q>

This code:

var Serious = null;
if (Serious === null) {Serious = {};}

validates without problems in JSLint, and here Serious is /pre-declared
before the first usage/ in the common programming sense, not in the
twisted hack you read out of ECMA.

Now take this code for validation:

if (Serious === null) {var Serious = {};}

Problem at line 1 character 28: Var Serious was used before it was
declared.
if (Serious === null) {var Serious = {};}
Problem at line 1 character 28: Identifier 'Serious' already declared
as global
if (Serious === null) {var Serious = {};}

What an f word is that? First warning sure refers to the fact that I
did not pre-declare Serious in the normal programming way shown before.

Second warning refers to the fact that Serious was pre-declared with
value undefined on the parsing stage (by the fact that tokens var and
Serious were found somewhere in the source separated by whitespace).
Now program warns me that I re-instantiate already existing variable.

So the variable doesn't exist (first warning) and do exist (second
warning). Nice. Great.

The first warning corresponds to the JSLing policy I quoted before. I
have a sneaky suspicion who squeezed the second nonsense in. No names,
of course...

May 23 '06 #13

P: n/a
VK wrote:
VK wrote:
I thought it was supposed to be a code validator and cleaner,
not a curiosity store? <snip> that if they are smart and careful enough, they can avoid
pre-declaring variables in their code?

Richard Cornford wrote:
What are you talking about now?


I am not an angel but you are the most stubbering horns
into wall person I've seen so far.


Pot -> Kettle.
All the thread through you were saying that the line like
var Serious; // pre-declare for future use
did not existed and doesn't have to exist in the original program.
I am not that inarticulate.
You whole point was build on the statement that the first time the
character sequence "var Serious" occured in the source code, it was in
the line passed through the JSLint:
Unlikely, as I usually manage something approaching meaningful
sentences when I make a point.
if (Serious == null) {var Serious = {};}

You were stating that ECMA specs are covering this case (unfortunately
they are)
It would be unfortunate if a technical specification for a programming
language did not cover such cases.
and that the fact that the character sequence "var Serious"
is contained in the source code in any place is good enough to
have Serious as undefined (rather than to get an exception on
trying to use it).

Fine. Right.
Yes, basic javascript. Maybe not obvious but certainly something that
every javascript programmer can be expected to have understood after
their first year of seriously using the language. How long have you
been 'using' Javascript now?
Do you really state that /this/ is an Ok interpretation of the term
"pre-declare variable in your programs"?
There is no meaning to "pre-declared" in the context of javascript, so
no.
<http://www.jslint.com/lint.html>
<q>
JavaScript allows var definitions to occur anywhere within a function.
JSLint is more strict.
JSLint expects that a var will be declared only once, and that it will
be declared before it is used.
</q>
Did you find anything there supporting your assumption JSLint was
"supposed to be a code validator and cleaner"?
This code:

var Serious = null;
if (Serious === null) {Serious = {};}

validates without problems in JSLint, and here Serious is
/pre-declared before the first usage/
Not "pre-declared", just declared.
in the common programming sense,
How would you know?
not in the twisted hack you read out of ECMA.
That twisted hack being the well-specified behaviour exhibited by all
ECMAScript implementations?
Now take this code for validation:

if (Serious === null) {var Serious = {};}

Problem at line 1 character 28: Var Serious was used before it was
declared.
if (Serious === null) {var Serious = {};}
Problem at line 1 character 28: Identifier 'Serious' already declared
as global
if (Serious === null) {var Serious = {};}

What an f word is that? First warning sure refers to the fact
that I did not pre-declare Serious in the normal programming way
shown before.
No, it refers to the fact that it was not declared prior to its fist
use.
Second warning refers to the fact that ... <snip>

The second warning is irrelevant as like many similar programs errors
and warnings may follow as the consequence of a first but not have any
real significance because fixing the first will resolve the conditions
that produce them.
So the variable doesn't exist (first warning) and do exist (second
warning). Nice. Great.
But irrelevant as soon as the first warning is corrected.
The first warning corresponds to the JSLing policy I quoted before. I
have a sneaky suspicion who squeezed the second nonsense in. No
names, of course...


You have no idea what you are talking about, again.

Richard.

May 23 '06 #14

P: n/a
VK

Richard Cornford wrote:
Did you find anything there supporting your assumption JSLint was
"supposed to be a code validator and cleaner"?


http://www.jslint.com/lint.html>
"JSLint, a JavaScript syntax checker and validator"

On the rest opt-out: until your first advise to anyone in this group to
pre-declare used variables in her/his code.

As you don't know what does this programming term mean - if it exists
at all, it will be explained on one of occasions mentioned above.

May 23 '06 #15

P: n/a
Guys!

Such a battle. A previous grudge or a fresh one?

Just to clarify, my code does not have any other declaration of
Serious. I just put the line

if (Serious == null) {var Serious = {};}

into www.jslint.com
Richard Cornford wrote:
Silly? I am being factually accurate; the variable is declared and we
can see that it is being declared (we, in this case, referring to
people who understand javascript, not you).

It would if Serious had not been declared, but it has so that is not an
issue.


Does this mean that while evaluating the condition "Serious == null"
that the JavaScript interpreter has looked ahead to see the
declaration? That would be very strange but I find a lot of
JavaScript's activities very strange.

Thanks,
Peter

May 23 '06 #16

P: n/a
VK wrote:
Richard Cornford wrote:
Did you find anything there supporting your assumption
JSLint was "supposed to be a code validator and cleaner"?
http://www.jslint.com/lint.html>
"JSLint, a JavaScript syntax checker and validator"


So nothing about it being a "cleaner"?
On the rest opt-out: until your first advise to anyone
in this group to pre-declare used variables in her/his
code.
Using "pre-declare" is meaningless, and potentially misleading in
javascript. Any variable declaration is acted upon prior to the
execution of code for the execution context, and all variable
declarations for the context are handled at the same time. So there is
no meaning in qualifying 'declaration' or 'declare' with 'pre-', 'post-'
or anything else. Variables are just declared, no more and no less.
As you don't know what does this programming term mean
I know that it is meaningless in the context of javascript.
- if it exists at all, it will be explained on one
of occasions mentioned above.


What are you whittering on about now?

Richard.
May 23 '06 #17

P: n/a
In article <11*********************@i40g2000cwc.googlegroups. com>, VK
<sc**********@yahoo.com> writes

<snip>
not in the
twisted hack you read out of ECMA.

<snip>

There's JavaScript. There's JScript. There's ECMAScript.

Then there's VKScript. I wish there was a separate news group for people
who want to talk about VKScript.

John
--
John Harris
May 23 '06 #18

P: n/a
VK
pe**********@gmail.com wrote:
Such a battle. A previous grudge or a fresh one?
A previous one... This time he got me. Damn his left hook to the head
with the Identifiers pre-processing... But I reached him couple of
times too, did you see?
:-) joking
Just to clarify, my code does not have any other declaration of
Serious. I just put the line

if (Serious == null) {var Serious = {};}

into www.jslint.com
So I was right in my guess. Really you should always spell the context
of your question.
Does this mean that while evaluating the condition "Serious == null"
that the JavaScript interpreter has looked ahead to see the
declaration? That would be very strange but I find a lot of
JavaScript's activities very strange.


No, it doesn't look ahead, it's even more funny as I see it. On the
parsing stage, when the program text is initially loaded and studied
for tokens, interpreter collects all occurences of
[var][white-space][literal]. These [literal] are being marked as
pre-declared with value undefined. When the script execution starts,
these [literal] are treated as pre-declared with value undefined.

this is why say

<script type="text/javascript">
if (foobar == null) {foobar = {};}
</script>

will cause "foobar is not defined" error but

<script type="text/javascript">
if (foobar == null) {var foobar = {};}
</script>

will be fine. The most ridiculous mechanics I ever seen, this is why it
squeezed so hard into my mind. I guess Brendan Eich knows why did they
do this way (one of "durt coding tolerance" things?)

May 23 '06 #19

P: n/a
pe**********@gmail.com wrote:
Guys!

Such a battle. A previous grudge or a fresh one?
An old one. VK has a serious habit of posting fictions originating in
his deranged mind. That results in much effort being wasted correcting
him, so that those who cannot appreciate for themselves how very little
he understands javascript, and how much he makes up off the top of his
head, are not taken in and don't make the mistake of believing his
nonsense. While other people, upon being correct, tend to learn and not
repeat their mistakes, VK's insanity prevents him from seeing that he is
ever wrong at all. Either he never accepts that he is wrong, and so
repeats his nonsense indefinitely, or it takes a monumental effort to
beat the truth into him (as in this case) and even then he tends to
still misconceive the result.
Just to clarify, my code does not have any other
declaration of Serious. I just put the line

if (Serious == null) {var Serious = {};}

into www.jslint.com

Richard Cornford wrote:
Silly? I am being factually accurate; the variable is declared
and we can see that it is being declared ... <snip> It would if Serious had not been declared, but it has so that
is not an issue.
Does this mean that while evaluating the condition
"Serious == null" that the JavaScript interpreter has
looked ahead to see the declaration?


The interpreter has looked ahead and seen the entire code. It acts upon
variable declarations prior to executing code for the execution context
in question. Which means that for a function local variable the
declaration is acted upon prior to the execution of any function body
code. The assignment of a value to the variable does not happen until
the assignment operation is evaluated during the execution of the
function body code.
That would be very strange
It is not that strange. Javascript's scoping units are functions so
there is no need to delay the creation of properties of the Variable
object; any declared variable should be visible within all of the
function in which it is declared.
but I find a lot of
JavaScript's activities very strange.


Like all programming languages, javascript is completely logical,
consistent and predictable in its behaviour. That makes it entirely
possible to completely understand javascript, so long as you are capable
of rational thought.

Richard.
May 23 '06 #20

P: n/a
VK wrote:
pe**********@gmail.com wrote:
Such a battle. A previous grudge or a fresh one?
A previous one... This time he got me. Damn his left
hook to the head with the Identifiers pre-processing...
But I reached him couple of times too, did you see?


You are deluding yourself.
:-) joking
Just to clarify, my code does not have any other
declaration of Serious. I just put the line

if (Serious == null) {var Serious = {};}

into www.jslint.com
So I was right in my guess. Really you should always
spell the context of your question.


Just utterly mistaken about the consequences of there being no other
declaration of the variable.
Does this mean that while evaluating the condition
"Serious == null" that the JavaScript interpreter has
looked ahead to see the declaration? That would be very
strange but I find a lot of JavaScript's activities very
strange.


No, it doesn't look ahead, it's even more funny as I see it. ...

<snip - more VK fiction>

But you don't "see it", except in your own head.
... . The most ridiculous mechanics I ever seen,
this is why it squeezed so hard into my mind.
Not because of all the crap you have in there to start with?
I guess
Brendan Eich knows why did they do this way (one of "durt
coding tolerance" things?)


It was much more likely designed to keep the implementation of the
function scoping units simple and quick.

Richard.
May 23 '06 #21

P: n/a
Richard Cornford wrote:
pe**********@gmail.com wrote:

VK has a serious habit of posting fictions originating in
his deranged mind. That results in much effort being wasted correcting
him
No offense to VK, but probably many people don't understand JavaScript
all that well. It is not so usual compared to the C/C++/Java people
learn at school. (I vote for Ruby in browsers!)
Like all programming languages, javascript is completely logical,
consistent and predictable in its behaviour. That makes it entirely
possible to completely understand javascript, so long as you are capable
of rational thought.


....and have a good book to read. Much of this could be solved with a
good book. Where is the good book on JavaScript? I'm not talking about
a nitty gritty, line-by-line look at a JavaScript interpreter but and
intermediate/intermediate-advanced book on JavaScript. Something that
can come after javascript: The Definitive Guide 4th ed.

Peter

May 23 '06 #22

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:
pe**********@gmail.com wrote:

VK has a serious habit of posting fictions originating
in his deranged mind. That results in much effort being
wasted correcting him
No offense to VK, but probably many people don't
understand JavaScript all that well.


But most people realise when they don't understand something that well.
VK is so mad that he actually thinks he is the only person with any real
understanding of javascript. That is why he goes blindly on repeating
the same nonsense, never listening to anyone repeatedly telling him he
is wrong. After all, why would I have to repeat that conditional
variable declarations did not exist in javascript if he was not utterly
convinced that I do not know what I am talking about? He didn't get that
idea from reading and understanding my posts, he can only believe that
as a result of assuming that anyone who doesn't agree with him must be
mistaken.

Also, bear in mind that VK claims to have been scripting browsers for
about 10 years. To have failed to understand even the basics in that
time is pretty poor, but superficial success over an extended period,
and avoiding contact with anyone who has a real understanding, obviously
can promote self delusion on his scale.
It is not so usual compared to the C/C++/Java people
learn at school. (I vote for Ruby in browsers!)
If all browser manufacturers implemented Ruby tomorrow we would be able
to use it in about 6 years time. So get used to javascript in browser
;-)
Like all programming languages, javascript is completely
logical, consistent and predictable in its behaviour. That
makes it entirely possible to completely understand javascript,
so long as you are capable of rational thought.


...and have a good book to read. Much of this could be solved
with a good book. Where is the good book on JavaScript?


If there were good books. If asked we have no choice but recommend the
least bad javascript book (javascript: The Definitive Guide, By David
Flanagan), and some of the rest are so bad that you would be worse off
reading them than not.
I'm not talking about a nitty gritty, line-by-line look
at a JavaScript interpreter but and
intermediate/intermediate-advanced book on JavaScript.
It is not an easy read, but ECMA 262 (3ed Ed.) would be my reading
recommendation if you want to understand the language. But you don't
learn about the interpreter(s) from that document as the language is
defined in terms of its required behaviour and the implementation then
left to the implementers.
Something that can come after javascript: The Definitive
Guide 4th ed.


In that case are you thinking about script design issues rather than
javascript as a programming language?

Richard.
May 23 '06 #23

P: n/a
> > (I vote for Ruby in browsers!)

If all browser manufacturers implemented Ruby tomorrow we would be able
to use it in about 6 years time. So get used to javascript in browser
;-)
I say they start working on it now! I'll be very happy in 6 years :D

It is not an easy read, but ECMA 262 (3ed Ed.) would be my reading
recommendation if you want to understand the language. But you don't
learn about the interpreter(s) from that document as the language is
defined in terms of its required behaviour and the implementation then
left to the implementers.


I'll take a closer look.

Something that can come after javascript: The Definitive
Guide 4th ed.


In that case are you thinking about script design issues rather than
javascript as a programming language?


One of each please.

Perhaps a book about JavaScript as an implementation of ECMA. This
would be a readable version of ECMA 262 (3rd Ed.) targeted to
JavaScript developers.

The other book would be about script design and modern professional
JavaScript (whatever that means.) Working with OOP in JavaScript,
simulated namespaces (eg. yahoo.js) and other stuff you use after you
get past JavaScript for just making tags like (untested)

<a href="http://www.example.com" onclick='alert("thanks for
clicking");'>

There is a lot of JavaScript info in books and on the internet that
slowed down my JavaScript beginnings. Definitely tarnishes the
language's appeal.

Peter

May 23 '06 #24

P: n/a
pe**********@gmail.com wrote:
> (I vote for Ruby in browsers!)
If all browser manufacturers implemented Ruby tomorrow we
would be able to use it in about 6 years time. So get used
to javascript in browser ;-)


I say they start working on it now! I'll be very happy in
6 years :D


It is a Catch 22 situation; it won't be implement now because nobody
will be able to use it usefully for 6 years so there is no point making
the effort, but unless it is implemented now it won't even be being used
in 6 years. On the other hand javascript is a very capable language
(well beyond the usual perception of it) so there is no real need for an
(or another) alternative.

<snip>
Something that can come after javascript: The Definitive
Guide 4th ed.


In that case are you thinking about script design issues
rather than javascript as a programming language?


One of each please.

Perhaps a book about JavaScript as an implementation of ECMA.
This would be a readable version of ECMA 262 (3rd Ed.) targeted
to JavaScript developers.


If well done that might be a good idea.
The other book would be about script design and modern
professional JavaScript (whatever that means.)
It probably doesn't mean much. The majority of current commercial
practice is not up to much, and there are not many people actually
employed as professional javascript authors (and fewer who should be).
Working with OOP in JavaScript,
There is certainly a deficit in appreciation of how javascript's
prototype inheritance differs from class-based inheritance (and the
implications of those differences on how OO should be implemented).
simulated namespaces (eg. yahoo.js)
Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript must
resolve those long property accessors each and every time they are used.
In addition, it is questionable whether the perceived namespace issue is
real to start with. I work on an application framework with a code base
of 60,000 lines of client-side javascript and don't see any problem with
naming collisions at all. If two objects are well named and share the
same name then they are doing the same task, so one of them is redundant
and should not be there. There just are not enough objects in that
system for namespaces to be an issue, and that is a very extreme system.

That will be true of any real-world implementation. You only need
namespaces if you are going to create a theoretically infinitely larger
system, but that is just not going to happen in real implementations.
The situation is not like making an enormous collection of
classes/packages available in Java, where any can be loaded from the
local hard disc, there is simply no sense in even attempting to download
any substantial mass of javascript to a web browser such that namespaces
are needed at runtime.
and other stuff you use after you
get past JavaScript for just making tags like (untested)

<a href="http://www.example.com" onclick='alert("thanks for
clicking");'>
Yuck! (bothering users with pointless stuff that gets in their way;
certainly a design decision that people need to learn to avoid.)
There is a lot of JavaScript info in books and on the
internet that slowed down my JavaScript beginnings.
Definitely tarnishes the language's appeal.


Bad books are a problem (Danny Goodman has a lot to answer for).

Richard.
May 24 '06 #25

P: n/a
Richard Cornford wrote:
There is certainly a deficit in appreciation of how javascript's
prototype inheritance differs from class-based inheritance (and the
implications of those differences on how OO should be implemented).
Isn't there a good chance that class based inheritance is in
JavaScript's future? I remember seeing Netscape JavaScript 3 Proposed
changes with classes and other stuff. Of course, we won't be able to
use it for six years.

simulated namespaces (eg. yahoo.js)


Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript must
resolve those long property accessors each and every time they are used.


So it would be better just to use a prefix to uniquify things?
Something like

YahooEvent.AddListener()

instead of

Yahoo.Event.addListener()

?

You work for Yahoo!, correct? What do you think about the use of pseudo
namespaces in that library (ie. the yahoo.js script)?

In addition, it is questionable whether the perceived namespace issue is
real to start with.
If Prototype.js used a pseudo namespace wouldn't that mean they would
have a smaller chance of breaking other JavaScript like for-in loops?
Maybe namespaces could protect unknowing programmers. Not that it is a
great argument but it is somewhat practical.

That will be true of any real-world implementation. You only need
namespaces if you are going to create a theoretically infinitely larger
system, but that is just not going to happen in real implementations.
The situation is not like making an enormous collection of
classes/packages available in Java, where any can be loaded from the
local hard disc, there is simply no sense in even attempting to download
any substantial mass of javascript to a web browser such that namespaces
are needed at runtime.


I suppose there will be a larger and larger base of libraries that
people can use in their projects. As the available bulk of libraries
increases there is a chance of a namespace between any two. That is
what I was thinking about.
-Peter

May 24 '06 #26

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:

[...]
In addition, it is questionable whether the perceived namespace issue is
real to start with.


If Prototype.js used a pseudo namespace wouldn't that mean they would
have a smaller chance of breaking other JavaScript like for-in loops?
Maybe namespaces could protect unknowing programmers. Not that it is a
great argument but it is somewhat practical.


That's not a good example. Prototype.js could create its own array
constructor (say called PTArray), then modify its prototype, leaving the
built-in Array alone. The author *chose* to modify the default
built-in object (well, its prototype).

Had programmers been given a choice of creating a PTArray or a standard
Array, they could look at the code and say "Hmm, no PTArray, let's
remove that from the library for this application".

If decent documentation was available, they could even make sure that
none of the other functions they've used need PTArray either.

[...]

--
Rob
Group FAQ: <URL:http://www.jibbering.com/faq/>
May 24 '06 #27

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:
There is certainly a deficit in appreciation of how
javascript's prototype inheritance differs from class-based
inheritance (and the implications of those differences on
how OO should be implemented).
Isn't there a good chance that class based inheritance is
in JavaScript's future? I remember seeing Netscape
JavaScript 3 Proposed changes with classes and other stuff.
Of course, we won't be able to use it for six years.


That is JavaScript(tm) 2 and, if ratified, will be ECMAScript 4th
edition. There will be no widespread implementation until it is ratified
(at least two years overdue at the moment) and it will not be practical
to use for 6 years after that.
> simulated namespaces (eg. yahoo.js)


Simulated namespaces are a very questionable notion. In
other language the namespaces are resolved when the code
is compiled. Javascript must resolve those long property
accessors each and every time they are used.


So it would be better just to use a prefix to uniquify things?
Something like

YahooEvent.AddListener()

instead of

Yahoo.Event.addListener()


Better, but not by much. If the final object is given a name that says
something meaningful about what it actually does then a second object
with the same name should be doing the same job, and so not needed in
any system using the first.
You work for Yahoo!, correct?
No.
What do you think about the use of pseudo namespaces
in that library (ie. the yahoo.js script)?
Its use is a reason for not using yahoo's code in its original form.
In addition, it is questionable whether the perceived
namespace issue is real to start with.


If Prototype.js used a pseudo namespace wouldn't that mean
they would have a smaller chance of breaking other JavaScript
like for-in loops?


The for-in loop issues is a consequence of extending the prototypes of
built-in object, and cannot be addressed with the use of simulated
namespaces.
Maybe namespaces could protect unknowing programmers. Not
that it is a great argument but it is somewhat practical.


Protect them form identifying meaningful names for the objects they
create?
That will be true of any real-world implementation. You
only need namespaces if you are going to create a
theoretically infinitely larger system, but that is just
not going to happen in real implementations. The situation
is not like making an enormous collection of classes/packages
available in Java, where any can be loaded from the local
hard disc, there is simply no sense in even attempting to
download any substantial mass of javascript to a web browser
such that namespaces are needed at runtime.


I suppose there will be a larger and larger base of libraries
that people can use in their projects. As the available bulk
of libraries increases there is a chance of a namespace between
any two. That is what I was thinking about.


Naming collisions only happen in an execution environment. Any
increasing availability of javascript libraries does not imply
downloading them all to the browser so that they would all be exposed to
the same execution environment. Indeed doing anything of the sort would
be crazy. The situation does not parallel languages like Java, you only
send the code you need to the browser, and that is not going to
indefinitely large or contain unknown code.

Richard.
May 24 '06 #28

P: n/a
VK wrote:
pe**********@gmail.com wrote: [...]
Does this mean that while evaluating the condition "Serious == null"
that the JavaScript interpreter has looked ahead to see the
declaration? That would be very strange but I find a lot of
JavaScript's activities very strange.


No, it doesn't look ahead, it's even more funny as I see it. On the
parsing stage, when the program text is initially loaded and studied
for tokens, interpreter collects all occurences of
[var][white-space][literal]. These [literal] are being marked as
pre-declared with value undefined. When the script execution starts,
these [literal] are treated as pre-declared with value undefined.

this is why say

<script type="text/javascript">
if (foobar == null) {foobar = {};}


It errors because in neither statement is foobar declared.

I guess that, where foobar has not been declared, statements like:

function blah(){
foobar = 5;
}

create foobar as a global variable to provide a simple way of creating
globals from inside a function. Insistence on the use of 'var' would
require that all globals were declared outside functions, or that the
scope be named in the declaration. This behaviour is also unique to
functions, it does not happen with other objects:

var a = {};
a.b;

creates b as an undefined property of a, there is no need (it's a syntax
error) to write:

var a.b;

or

var a = {var b};
It makes the language more tolerant of programmers who forget to declare
variables - though it might have unexpected consequences. Good
programmers will still write:

var foobar;
function blah(){
foobar = 5;
}

[...]
I guess Brendan Eich knows why did they do this way


Why not ask him? His e-mail address can be found here:

<URL:http://www.mozilla.org/about/staff>
JavaScript was intended to be a simple, forgiving language for web
developers who did not want to learn a full-blown OO language like C++
or Java (at the time Java was touted as the way to make pages
interactive - thank heavens for Mocha/LiveScript/JavaScript).

Its widespread use is a sign that it has succeeded (wildly) - almost to
the total exclusion of other web page scripting or programming
languages. So despite its shortcomings, it can't be all that bad at
what it does.
--
Rob
Group FAQ: <URL:http://www.jibbering.com/faq/>
May 24 '06 #29

P: n/a
Richard Cornford wrote:

Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript must
resolve those long property accessors each and every time they are used.


What are the implications of this statement on the discussion of "Class
Methods" in JavaScript? In particular I am looking at page 126 of
javascript: The Definative Guide 4th ed. In the example, he has a class
called "Circle" and wants a class menthod called "max".

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
Circle.max = Circle_max;

This example seems like a real mess. Why clutter the global namespace
with Circle_max? Maybe there is some other reason but given that we
probably will only ever call Circle.max we have two better options

Option 1 directly create a class method

function Circle(radius){ stuff }
Circle.max = function(a,b){ stuff };

Option 2 use a function instead of a class method

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }

In some languages, like Java, Option 1 would allow Circle.max access to
class variables. I think that this is not really an issue in JavaScript
because nothing is private, true? However Option 1 will have slower
execution speed because the interpreter must resolve the '.' every time
we use Circle.max().

So we could/should just use Option 2 which doesn't have much namespace
collision possiblity anyway.

So what the heck was he arguing about when he said on page 126 that
"associating these function with a class gives them a convenient niche
in the JavaScript namespace and prevents namespace collisions." There
is no real benifit and a small perfomance decrease.

Is the objects chapter of this book getting worse the more I read it or
am I out to lunch here?

Thanks,
Peter

May 25 '06 #30

P: n/a
VK

petermich...@gmail.com wrote:
I am looking at page 126 of
javascript: The Definative Guide 4th ed. In the example, he has a class
called "Circle" and wants a class menthod called "max".

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
Circle.max = Circle_max;

This example seems like a real mess. Why clutter the global namespace
with Circle_max? Maybe there is some other reason but given that we
probably will only ever call Circle.max we have two better options

Option 1 directly create a class method

function Circle(radius){ stuff }
Circle.max = function(a,b){ stuff };
If he was writting his book right now he would most probably use direct
function object augmentation (like above).
It was not thought this way that time yet. All closure/pseudo-protected
members and other things were in the languages nearly since Netscape 3
- but it took 10 years before "discover" them and find for them some
practical use. It's like with math - some formal structures can float
around for centuries before new physics demands fill them with a
practical content.
AFAIK the concept itself of anonymous function expression used in the
right side of assignment is backtracked only to the beginning of this
century - and developed by cabbal members of c.l.j. in their studies of
closures. That is by my (definitely not definitive) archive researches.
How "obvious" it is until one saw it - it still requires an extra
initial abstraction effort.
Option 2 use a function instead of a class method

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
That effectively brings us back to the old "Macromedia Notation" used
during the Internet Bubble:
Two capital letter denoting the producer - underscore - constructor
name - underscore - method name:
MM_Circle_getRadius
VK_Foo_setFoobar

That also provide a reasonable reliable namespace protection, but in
the modern OOP terms looks ... lame, no cool :-)
In some languages, like Java, Option 1 would allow Circle.max access to
class variables. I think that this is not really an issue in JavaScript
because nothing is private, true?
There are different ways to achieve private status for members in the
conventional script, you may search this group archives.
There is nothing explicetly documented in JavaScript/JScript official
producers' manuals, that's true.
So what the heck was he arguing about when he said on page 126 that
"associating these function with a class gives them a convenient niche
in the JavaScript namespace and prevents namespace collisions."


I presume he did not mean the technical method itself, but the used
naming schema, where all "function-methods" uniformly start with the
main constructor name.

May 25 '06 #31

P: n/a
VK

VK wrote:
How "obvious" it is until one saw it - it still requires an extra
initial abstraction effort.


.... One more attempt :-) :

However "obvious" it is after one saw it still requires an extra
initial abstraction effort.

May 25 '06 #32

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:

Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript
must resolve those long property accessors each and every time they
are used.
What are the implications of this statement on the discussion of "Class
Methods" in JavaScript? In particular I am looking at page 126 of
javascript: The Definative Guide 4th ed. In the example, he has a
class called "Circle" and wants a class menthod called "max".

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
Circle.max = Circle_max;

This example seems like a real mess. Why clutter the global
namespace with Circle_max?


Yes, why do that? One of the reasons that JavaScript the Definitive
Guide is only the least bad javascript book available.
Maybe there is some other reason but given that we
probably will only ever call Circle.max we have two better
options

Option 1 directly create a class method

function Circle(radius){ stuff }
Circle.max = function(a,b){ stuff };

Option 2 use a function instead of a class method

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }

In some languages, like Java, Option 1 would allow Circle.max
access to class variables. I think that this is not really an issue
in JavaScript
It could be an issue as - Circle.max() - could access other properties
of the constructor through the - this - keyword.
because nothing is private, true?
Well, things put into closures can be restricted in their accessibility
in ways that can resembles notions of 'private'.
However Option 1 will have slower execution speed because the
interpreter must resolve the '.' every time we use Circle.max().
The overhead per dot is not that great so how significant it is depends
a bit on how often you call the static method, and generally static
methods are not used that often. My issue with it is the number of dots
in a simulated namespace and the frequency with witch they would need
to be resolved.
So we could/should just use Option 2 which doesn't have much
namespace collision possiblity anyway.
Not necessarily. The concept of methods that are 'of the class' is well
expressed by making the methods properties of the constructor. If the
functions that are placed in that role really are suited then a small
overhead on the infrequent occasions that they would be referenced
doesn't seem like too great a cost to pay for the ability to associate
genuinely related facilities in a well defined unit.

There are many functions that could be strongly related to a particular
'class', such as virtually any function that acts upon multiple
arguments that must be instances of that 'class' (for example, a
compare function for use when sorting arrays of Circle instances), or
functions that implement concepts closely related to objects of a type
but not necessarily instances of that type (such as a method retiring
the surface area of a circle given its radius).

Where the namespace simulation may have:-

Something.Circle

- the existence of that initial - Something - implies that there may be
more than one 'Circle' in the system, and if they are well named the
implication would be that one or other would be redundant and that one
could be removed and the other used, or an amalgam of the two called
'Circle' would be more appropriate.
So what the heck was he arguing about when he said on page 126 that
"associating these function with a class gives them a convenient niche
in the JavaScript namespace and prevents namespace collisions."
It does prevent namespace collisions. The method in question is called
'max', which happens to also be the name of a static method of the Math
object.
There is no real benifit and a small perfomance decrease.

<snip>

There is a benefit, but the simulated namespace notion takes avoiding
namespace collisions far beyond collecting related functionality.
Exaggerating the performance decrease while addressing an issue that is
not nearly significant enough to justify such an extreme response.

Richard.

May 25 '06 #33

P: n/a
Regarding namespaces,

Richard Cornford wrote:
(Regarding name resolution)

The overhead per dot is not that great so how significant it is depends
a bit on how often you call the static method, and generally static
methods are not used that often. My issue with it is the number of dots
in a simulated namespace and the frequency with witch they would need
to be resolved.


I see you haven't pointed out this overhead in your replies to me in the
other thread. Would I be correct in the assumption that having only one
level (one dot) is not problematic?

- the underlying implementation is probably a hashtable or other O(1)
lookup structure

- global names must be resolved, so we have always at least t time for
resolution

- if there is only one dot, then resolution takes 2t

- if the underlying implementation is worse than O(1), then it's best to
divide the lists anyway, and a one dot system may be a good way to do that

From your rationale, I get that you object to Something.Circle.member,
but not necessarily to Circle.member, and think the latter is probably
better than circleMember. Both would be my opinion also, but I'd like to
have some confirmation. I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members' each

than

1000 members of the global namespace

but if I'm missing something, I'd like to be told so.
--
am

laurus : rhodophyta : brezoneg : smalltalk : stargate
May 25 '06 #34

P: n/a
VK wrote:
AFAIK the concept itself of anonymous function expression used in the
right side of assignment is backtracked only to the beginning of this
century - and developed by cabbal members of c.l.j. in their studies of
closures.


You have heard of Lisp or Smalltalk? Javascript was modelled after Self,
a protoype-based 'version' of Smalltalk.
Unfortunately, the majority of programmers are oblivious to anything
other than C-like languages, and so javascript has been awfully misused
for years. But it's not like nobody knew better.
--
am

laurus : rhodophyta : brezoneg : smalltalk : stargate
May 25 '06 #35

P: n/a

António Marques wrote:
I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members' each

than

1000 members of the global namespace


Why is this? Are you suggesting that with 1000 members in the global
namespace that the interpreter might have to look through 1000 names to
find the correct function. And with the 20-50 system only look through
a maximum of 70 names?

Peter

May 25 '06 #36

P: n/a
António Marques wrote:
Regarding namespaces,

Richard Cornford wrote:
(Regarding name resolution)

The overhead per dot is not that great so how significant it is depends
a bit on how often you call the static method, and generally static
methods are not used that often. My issue with it is the number of dots
in a simulated namespace and the frequency with witch they would need
to be resolved.
I see you haven't pointed out this overhead in your replies to me in the
other thread. Would I be correct in the assumption that having only one
level (one dot) is not problematic?


Generally no. There is at least one dot when you reference an instance
member with the - this - keyword.
- the underlying implementation is probably a hashtable or
other O(1) lookup structure
And then there is IE.
- global names must be resolved, so we have always at least t
time for resolution
Scope chain resolution of global variables/functions should be
proportional to the depth of the scope chain when the reference is
made. It will usually be two objects deep in normal functions code.
- if there is only one dot, then resolution takes 2t
I would not put money on that, and certainly not as a general statement
about all implementations.
- if the underlying implementation is worse than O(1), then it's best to
divide the lists anyway, and a one dot system may be a good way
to do that
Only up to a point.
From your rationale, I get that you object to Something.Circle.member,
but not necessarily to Circle.member, and think the latter is probably
better than circleMember.
I also think it is, so long as - member - is a method that really
should belong to Circle.
Both would be my opinion also, but I'd like to
have some confirmation. I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members'
each than

1000 members of the global namespace

but if I'm missing something, I'd like to be told so.


Generally I would too, but I would not worry much about having 200
globals with 5 members each, so long as the globals were the right
objects to have and their members really should belong to them.

Richard.

May 25 '06 #37

P: n/a
pe**********@gmail.com wrote:
António Marques wrote:
I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members' each
than

1000 members of the global namespace

Why is this? Are you suggesting that with 1000 members in the
global namespace that the interpreter might have to look through
1000 names to find the correct function.

<snip>

Actually it might. But most implementers appear to have been smart
enough to use hash-table like objects to implement javascript's dynamic
objects so in those cases the number of properties on an object doesn't
make much difference to the time or effort involved in finding one.

A better reason for worrying about having so many objects in a single
scope would be the effort involved in managing them. But it is not a
realistic scenario as 1000 objects/functions/properties is a great deal
of javascript so unless everything in the entire system was global that
would imply a script far too large to even consider sending to a
browser.

Large systems are better created in an OO style, and then the vast bulk
of the javascript code will be in (hopefully anonymous) functions
assigned as properties of the constructor functions' prototypes
(becoming methods of the object instances). If you are doing that and
still had 1000 global properties the whole system would be enormous.

It is the fact that even a big system in an OO style will not have an
unmanageable number of global properties if it is going to be viable to
be sending it all to a web browser, that encourages me to think that
namespace simulation is unnecessary.

Richard.

May 25 '06 #38

P: n/a
Richard Cornford wrote:
From your rationale, I get that you object to Something.Circle.member,
but not necessarily to Circle.member, and think the latter is probably
better than circleMember.


I also think it is, so long as - member - is a method that really
should belong to Circle.


Better by what criteria?

Both would be my opinion also, but I'd like to
have some confirmation. I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members'
each than

1000 members of the global namespace

but if I'm missing something, I'd like to be told so.


Generally I would too,


What makes it better?

I'm starting to think your reasons are programmer preference. That is
fine if it makes the code more maintainable for you. However if there
is a perfomance bottleneck then I would have no problem writing
Circle_member rather than Circle.member. I don't use underscore much in
JavaScript anyway so they both look the same to me.

Peter

May 25 '06 #39

P: n/a

Richard Cornford wrote:
pe**********@gmail.com wrote:
António Marques wrote:
I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members' each
than

1000 members of the global namespace

Why is this? Are you suggesting that with 1000 members in the
global namespace that the interpreter might have to look through
1000 names to find the correct function.

<snip>

Actually it might. But most implementers appear to have been smart
enough to use hash-table like objects to implement javascript's dynamic
objects so in those cases the number of properties on an object doesn't
make much difference to the time or effort involved in finding one.


I just tested this in FireFox. In the tests below it looks like the
1000 members way took between 650-800 ms. The 20-50 method took between
700-850 ms.

<html>
<head>

<script type='text/javascript'>
var i;
var j;

for(i=0;i<50;i++){
eval("var Serious"+i+"={};");
for(j=0;j<20;j++){
eval("Serious"+i+".foo"+j+"=function(){};");
}
}

var start = new Date();
for (i=0;i<100000;i++){
Serious24.foo9();
}
var end = new Date();

alert(end-start);
</script>

</head>
<body>

</body>
</html>

<html>
<head>

<script type='text/javascript'>
var i;

for(i=0;i<1000;i++){
eval("function Serious_foo"+i+"(){};");
}

var start = new Date();
for (i=0;i<100000;i++){
Serious_foo499();
}
var end = new Date();

alert(end-start);
</script>

</head>
<body>

</body>
</html>

May 25 '06 #40

P: n/a
RobG wrote:
VK wrote:
[VK nonsense about pre-declaration]

this is why say

<script type="text/javascript">
if (foobar == null) {foobar = {};}

[errors]
It errors because in neither statement is foobar declared.


Full ACK.
I guess that, where foobar has not been declared, statements like:

function blah(){
foobar = 5;
}

create foobar as a global variable to provide a simple way of creating
globals from inside a function. [...]


No. This may read as me nitpicking again, but *still* _no_ /variable/
is created, but a property of the Global Object is (unless a superordered
execution context has a Variable Object with that property in which case
the property value changes). Either Brendan (Eich) had this in mind or he
did not care about the difference. However, since we know for some time
now that there is a scoping problem with the IE DOM, it is possible that
it may be elsewhere. Hence (and for the sake of transparent maintainable
code) this code style is considered harmful and recommended against. So
if you need an identifier, you better declare it.
PointedEars
May 25 '06 #41

P: n/a
Richard Cornford wrote:
pe**********@gmail.com wrote:
Richard Cornford wrote:
Silly? I am being factually accurate; the variable is declared
and we can see that it is being declared ... <snip> It would if Serious had not been declared, but it has so that
is not an issue.


Does this mean that while evaluating the condition
"Serious == null" that the JavaScript interpreter has
looked ahead to see the declaration?


The interpreter has looked ahead and seen the entire code.


The _compiler_ has.
PointedEars
--
When you have eliminated all which is impossible, then
whatever remains, however improbable, must be the truth.
-- Sherlock Holmes in Sir Arthur Conan Doyle's
"The Blanched Soldier"
May 25 '06 #42

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:
From your rationale, I get that you object to Something.Circle.member,
but not necessarily to Circle.member, and think the latter is probably
better than circleMember.
I also think it is, so long as - member - is a method that really
should belong to Circle.


Better by what criteria?


In this case it is better because the structure of the objects in the
environment reflects a real relationship between the roles of those
objects. Which is why I would insist that - member - must be suited to
being a member or Circle. If it is not is should not be associated with
the Circle object at all, and so may be more appropriate being a global
function.
Both would be my opinion also, but I'd like to
have some confirmation. I'd certainly prefer to have

20 members in the global namespace with 50 'sub-members'
each than

1000 members of the global namespace

but if I'm missing something, I'd like to be told so.


Generally I would too,


What makes it better?


Nothing makes it better as such. A sensible system of 1000 objects
would be expected to have, and so express, hierarchical relationships.
If no such relationships existed then there is no reason for there
being a hierarchical structure in the code.
I'm starting to think your reasons are programmer preference.
That is fine if it makes the code more maintainable for you.
My reasons are mostly that I like the structures used in javascript to
properly reflect the concepts being implemented. If being a method of a
constructor expresses the real relationship between the constructor
(the objects it constructs) and its method then it should be a property
of the constructor, else it should never be.

The namespace simulation idea proposed creating deep hierarchies of
object structures with no better reason for entire level existing in
that hierarchy than that namespaces are being simulated. That does not
strike me as a good reason for creating deep object structures, and the
justification that doing so avoids naming collisions is only convincing
to people who have seen the value of namespaces in languages with
enormous library/package collections and not seen that the issues
addressed there does not apply to a know, limited set of javascript
code intended to be downloaded to a web browser in its entirety.

Without a positive reason for simulating namespaces (no consequential
benefits) the performance degradation (no matter how small) only leaves
only a reason for not simulating namespaces.

However, not simulating namespaces because you only have a reason for
not doing so is not the same as not creating properties of constructors
because that suffers the same drawback as simulating namespaces. There
may be positive reasons for creating a property of a constructor that
outweigh the slight performance degradation of the extra lookup needed
to resolve the property accessor.
However if there is a perfomance bottleneck then I would
have no problem writing Circle_member rather than
Circle.member. I don't use underscore much in
JavaScript anyway so they both look the same to me.


It would be more of a performance degradation than a bottleneck. But
the best reason for deciding between Circle.member (or some other name)
and Circle.member when assigning a function is the relationship between
that function and Circle. The decision could go either way, depending
on the code.

Richard.

May 25 '06 #43

P: n/a
pe**********@gmail.com wrote:
Richard Cornford wrote:
Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript must
resolve those long property accessors each and every time they are used.
What are the implications of this statement on the discussion of "Class
Methods" in JavaScript? In particular I am looking at page 126 of
javascript: The Definative Guide 4th ed. In the example, he has a class
called "Circle" and wants a class menthod called "max".

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
Circle.max = Circle_max;


No, he has not! There are two Function objects with identifiers Circle and
Circle_max. The naming convention suggests that they are to be used as
constructors for an object. Then the first Function object is augmented
with a `max' property that becomes a method identifier because it is
assigned a reference to the second Function object (which subsequently can
be called as a method of the first Function object).
This example seems like a real mess. Why clutter the global namespace
with Circle_max?
Full ACK.
Maybe there is some other reason but given that we
probably will only ever call Circle.max we have two better options

Option 1 directly create a class method
You should stop thinking of client-side ECMAScript implementations in
terms of class-based object-oriented programming languages. Those are
prototype-based programming languages to date. The only production-level
ECMAScript (4) implementation that implements class-based programming
to date is JScript.NET, which is server-side only (and even if it was
client-side as well, it would be restricted to Microsoft applications).
function Circle(radius){ stuff }
Circle.max = function(a,b){ stuff };
This is a possibility, but not a reasonable one. For you will have only
one usable Circle object. If you use Circle as a constructor, the newly
created object --

var myCircle = new Circle(42);

-- will _not_ inherit the max() method, and you will have to

Circle.max.call(this, 42, 23);

and the like to affect the new object's properties. Therefore, you should
augment the constructor's prototype object instead:

function Circle(radius){ stuff }
Circle.prototype.max = function(a,b){ stuff };

Now you can create a new Circle object that will inherit the max() method
from the prototype object of the constructor through the prototype chain:

... myCircle.max(42, 23) ...
Option 2 use a function instead of a class method


Again, will you please recognize that there are no classes, hence no "class
method"s?

You will probably be better off burning Goodman's ... book, subscribing to
this newsgroup, and reading the ECMAScript Language Specification among
other reference material.
PointedEars
--
In the First World War, 13 million people were killed. In the Second
World War, 40 million people were killed. I think that if a third war
takes place, nothing is going to be left on the face of earth.
-- Shakira, 2003-02-05 @ MTV.com
May 25 '06 #44

P: n/a
In article <11**********************@i39g2000cwa.googlegroups .com>,
pe**********@gmail.com writes
Richard Cornford wrote:

Simulated namespaces are a very questionable notion. In other language
the namespaces are resolved when the code is compiled. Javascript must
resolve those long property accessors each and every time they are used.
What are the implications of this statement on the discussion of "Class
Methods" in JavaScript? In particular I am looking at page 126 of
javascript: The Definative Guide 4th ed. In the example, he has a class
called "Circle" and wants a class menthod called "max".

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }
Circle.max = Circle_max;

This example seems like a real mess. Why clutter the global namespace
with Circle_max? Maybe there is some other reason but given that we
probably will only ever call Circle.max we have two better options

Option 1 directly create a class method

function Circle(radius){ stuff }
Circle.max = function(a,b){ stuff };


Earlier versions of javascript didn't have function expressions, alias
anonymous functions. E.g In NN 4. The book goes back a long way.

Besides, he might be explaining that methods can be attached to objects,
leaving function expressions until later. (I haven't got the book so I
don't know for sure.)
Option 2 use a function instead of a class method

function Circle(radius){ stuff }
function Circle_max(a,b){ stuff }

In some languages, like Java, Option 1 would allow Circle.max access to
class variables. I think that this is not really an issue in JavaScript
because nothing is private, true? However Option 1 will have slower
execution speed because the interpreter must resolve the '.' every time
we use Circle.max().
Global variables and global functions are also properties so they still
go through the '.' process even though you don't have to type the dot.

Are you sure that the first, implicit, dot in Circle.max is going to be
no slower than the second, explicit, dot ? How would you measure it ?
So we could/should just use Option 2 which doesn't have much namespace
collision possiblity anyway.

So what the heck was he arguing about when he said on page 126 that
"associating these function with a class gives them a convenient niche
in the JavaScript namespace and prevents namespace collisions." There
is no real benifit and a small perfomance decrease.
Well, the function name can be so long it's unlikely to collide with
another one. If you never have to use the name because you write
Circle.max it doesn't matter if it's called
PetersCircleClassVersion1Max.

Obviously, if you don't need to worry about older browsers you use
Option 1.
Is the objects chapter of this book getting worse the more I read it or
am I out to lunch here?


It's a popular text book : 'nuff said.

John
--
John Harris
May 25 '06 #45

This discussion thread is closed

Replies have been disabled for this discussion.