Difference between findPos("divThis") and findPos(divThis)

C

Cal Who

I find that either of the two approches below work.I'd appreciate getting a
little insight into what is going on and the good and bad aspects of each
approach.Thanksfunction findPos(obj) {
var w = document.getElementById(obj).offsetWidth;
var h = document.getElementById(obj).offsetHeight;called with:
findPos("divThis")Orfunction findPos(obj) {
var w = obj.offsetWidth;
var h = obj.offsetHeight;called with: findPos(divThis)
 
T

Thomas 'PointedEars' Lahn

Cal said:
I find that either of the two approches below work.I'd appreciate getting
a little insight into what is going on and the good and bad aspects of
each approach. Thanks

function findPos(obj)
{
var w = document.getElementById(obj).offsetWidth;
var h = document.getElementById(obj).offsetHeight;
}

called with: findPos("divThis")

Or

function findPos(obj)
{
var w = obj.offsetWidth;
var h = obj.offsetHeight;
}
called with: findPos(divThis)

Your OP was hard to read and not even syntactically valid; I have
reformatted it and completed it. Please take more care next time.

Both approaches work in Internet Explorer and perhaps elsewhere in *Quirks
Mode*. That is so because MSHTML, probably to make DOM scripting easier,
elements with IDs are explicitly represented in the DOM by properties of the
same name of the object referred to by `window'.

That object (`window' object for short) is in the scope chain. So if you
use the `divThis' identifier and no other object in the scope chain has a
property of that name, it will be resolved to the property of the `window'
object. The result is a reference to the DOM element object which
represents the element.

You should not rely on this proprietary behavior, and you should avoid
triggering Quirks Mode.

That findPos() function call really is pointless, as the local variables
will not be visible outside the function here. So unless you want to
support IE/MSHTML 4 and NN 4, for which you would need a wrapper function,
KISS:

var o = document.getElementById("divThis");
var w = o.offsetWidth;
var h = o.offsetHeight;

But do not rely on that either; read the discussion about element dimensions
three days ago. (In general: search, read, post.)

BTW, findPos() does not what its name says.


PointedEars
 
C

Cal Who

Thomas 'PointedEars' Lahn said:
...

Your OP was hard to read and not even syntactically valid; I have
reformatted it and completed it.

Also, I should have included the "..." that (I just added) to make cleared
that there was more code.
Both approaches work in Internet Explorer and perhaps elsewhere in *Quirks
Mode*. That is so because MSHTML, probably to make DOM scripting easier,
elements with IDs are explicitly represented in the DOM by properties of
the
same name of the object referred to by `window'.

That object (`window' object for short) is in the scope chain. So if you
use the `divThis' identifier and no other object in the scope chain has a
property of that name, it will be resolved to the property of the `window'
object. The result is a reference to the DOM element object which
represents the element.

I don't have the backgroung to understand the above paragraph.
Is the first approch (var w = document.getElementById(obj).offsetWidth) the
better one?
You should not rely on this proprietary behavior, and you should avoid
triggering Quirks Mode.

That findPos() function call really is pointless, as the local variables
will not be visible outside the function here. So unless you want to
support IE/MSHTML 4 and NN 4, for which you would need a wrapper function,
KISS:

var o = document.getElementById("divThis");
var w = o.offsetWidth;
var h = o.offsetHeight;

But do not rely on that either; read the discussion about element
dimensions
three days ago. (In general: search, read, post.)

I did search. That's where I got the code I asked about.

If you are refering to: "How to Determine Positions of Elements"

I had read it and in fact have copied it and pasted into my file for later
testing, but he did not, I don't believe, mentioned this method which is
simpler and since I don't know why I should not rely on it I thought I'd try
it.
BTW, findPos() does not what its name says.

Good catch but I'm still developing " findPosAndSize"


Thanks
 
T

Thomas 'PointedEars' Lahn

Cal said:
Also, I should have included the "..." that (I just added) to make cleared
that there was more code.
ACK.


I don't have the backgroung to understand the above paragraph.

I will answer specific, *smart* questions you may have. (So do not ask,
for example, "What is a scope chain?", unless you want a "STFW" answer.)

<http://www.catb.org/~esr/faqs/smart-questions.html>

But I will still ignore you if you (continue to) post with an invalid
From/Reply-To header field value. Usenet can only work if communication
works both ways.
Is the first approch (var w = document.getElementById(obj).offsetWidth)
the better one?

Yes and no. It is the better one if you pass the element's ID string for
`obj'. It is not better if you call document.getElementById(obj) twice in
the process. There are also cases where you do not need to call
document.getElementById(); in that case it would be better not to call it.
If you are refering to: "How to Determine Positions of Elements"

I was referring to the thread started with
<Subject "David Mark's Javascript Tip Du Jour - Volume #1 - Tip #1234 - How
to Measure Element Dimensions", which is what your posted code does.
I had read it and in fact have copied it and pasted into my file for later
testing, but he did not, I don't believe, mentioned this method which is
simpler and since I don't know why I should not rely on it I thought I'd
try it.

Your posted code has nothing to do with the posting you are referring to.


Please trim your quotes to the relevant minimum next time.

<http://jibbering.com/faq/notes/posting>

HTH

PointedEars
 
C

Cal Who

But I will still ignore you if you (continue to) post with an invalid
From/Reply-To header field value. Usenet can only work if communication
works both ways.

I have no idea what it is about. I use IE Express and reply with "Reply
Group"
Do I have something set up wrong?
'
Yes and no. It is the better one if you pass the element's ID string for
`obj'. It is not better if you call document.getElementById(obj) twice in
the process. There are also cases where you do not need to call
document.getElementById(); in that case it would be better not to call it.

That's what I'll do then.

Thanks
 
J

J.R.

I have no idea what it is about. I use IE Express and reply with "Reply
Group"
Do I have something set up wrong?
'

That's what I'll do then.

Thanks

I always use obj as a reference to an element of the DOM. But I admit
there are cases in which you would like to receive either a string or an
element reference as the function's argument. In this case, try this code:

function getOuterDimensions(obj) {
var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth;
h = el.offsetHeight;
...

}

Please, have a look at the post called "David Mark's Javascript Tip Du
Jour - Volume #1 - Tip #1234 - How to Measure Element Dimensions".
 
J

J.R.

I always use obj as a reference to an element of the DOM. But I admit
there are cases in which you would like to receive either a string or an
element reference as the function's argument. In this case, try this code:

function getOuterDimensions(obj) {
var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth;
h = el.offsetHeight;
...

}

Correcting a typo:

var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth, // , instead of ;
h = el.offsetHeight;
 
C

Cal Who

var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth, // , instead of ;
h = el.offsetHeight;
That's neat.

Except for the commas!

I looked up comma operator but am still confused.

Wouldn't this be OK (better?)

var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;
w = el.offsetWidth ;
h = el.offsetHeight;
...
 
J

J.R.

That's neat.

Except for the commas!

I looked up comma operator but am still confused.

Wouldn't this be OK (better?)

var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;
w = el.offsetWidth ;
h = el.offsetHeight;
...

No, because the ";" marks the end of the variable declaration list. In
the above code, you are indeed creating an implied global variable
called h, instead of creating a private variable in the function scope.

it is one of the JavaScript best practices to declare all of the
variables used in a function at the top of the function body. You may
have many variables separated by commas, e.g

var el = ...,
h = ...,
w = ...,
i, j, len, ..., z;

You must not use multiple var statements such as:
var el;
var h = ...;
var z;
 
C

Cal Who

J.R. said:
No, because the ";" marks the end of the variable declaration list. In the
above code, you are indeed creating an implied global variable called h,
instead of creating a private variable in the function scope.

it is one of the JavaScript best practices to declare all of the variables
used in a function at the top of the function body. You may have many
variables separated by commas, e.g

var el = ...,
h = ...,
w = ...,
i, j, len, ..., z;

You must not use multiple var statements such as:
var el;
var h = ...;
var z;


Thanks a lot
 
D

Denis McMahon

it is one of the JavaScript best practices to declare all of the
variables used in a function at the top of the function body. You may
have many variables separated by commas, e.g
var el = ...,
h = ...,
w = ...,
i, j, len, ..., z;
You must not use multiple var statements such as:
var el;
var h = ...;
var z;

Rubbish.

You can use as many var statements as you like. Nothing in the standards
or the implementation prevents this, so "must not" is incorrect.

Some people think all variables should be declared in a single statement.
Some people use a different statement for each type of variable, where
type is the sort of data that it will be used to hold (array, string,
integer, float, object etc).
Some people just use one variable per var.

These are all permitted by the various standards, and they all work.
There is no reason that you "must" or "must not" do any of these.

Also, "best practice" is invariably "in the opinion of the author of the
website / book / blog / whatever" that said example of best practice
appears in. As a matter of interest, what's your reference for "best
practice"? If I write a book or start a blog called "Javascript - Best
Practice" does that make it true?

Rgds

Denis McMahon
 
J

J.R.

Rubbish.

You can use as many var statements as you like. Nothing in the standards
or the implementation prevents this, so "must not" is incorrect.

"must not" was exaggerated on purpose, because using many var statements
is an antipattern in JavaScript.
Some people think all variables should be declared in a single statement.
Some people use a different statement for each type of variable, where
type is the sort of data that it will be used to hold (array, string,
integer, float, object etc).
Some people just use one variable per var.

The advantages of using the Single var Pattern at the top of your
functions are:
- there's a single place to look for all the local variables needed by
the function;
- prevention of logical errors when a variable is used before it’s defined;
- Helps you remember to declare variables and therefore minimize globals;
- only one var statement means less code to type and a reduction in the
file size.

These are all permitted by the various standards, and they all work.
There is no reason that you "must" or "must not" do any of these.


Also, "best practice" is invariably "in the opinion of the author of the
website / book / blog / whatever" that said example of best practice
appears in.

There are patterns in any programming language usually adopted by
programmers as "best coding practices". And it happens to other fields
of study too. See <http://en.wikipedia.org/wiki/Best_Coding_Practices>

If you get a bunch of authors (books, blogs, etc.) that state the same
"best practices" in any programming language, then you can bet who is
wrong or right...
As a matter of interest, what's your reference for "best
practice"? If I write a book or start a blog called "Javascript - Best
Practice" does that make it true?

No, it doesn't, although I know you're a very experienced and smart
programmer. However, if you published some evidence such as performance
tests, etc., then you could state that some practice should be either
considered a good one or avoided altogether.
 
T

Thomas 'PointedEars' Lahn

Cal said:
I have no idea what it is about. I use IE Express

You mean _Outlook_ Express, as it says in the `X-Newsreader' header field of
your postings [1].
and reply with "Reply Group"
Do I have something set up wrong?
'

Yes. One cannot send e-mail to your sender (`From') "address" (which
therefore isn't one). This violates NetNews/Internet standards and
disregards Netiquette (network etiquette).

(And a comparably minor thing: There is a leading space in your "name",
which should be your real name.)


F'up2 poster (i. e., please reply by e-mail *only*; check headers before you
send, as your outdated program has a bug there – by default it sends to the
newsgroup, too [2]. TIA.)

PointedEars
___________
[1]
<http://email.about.com/od/outlookex...r_Lines_Windows_Live_Mail_Outlook_Express.htm>
[2] <http://insideoe.com/>
 
T

Thomas 'PointedEars' Lahn

J.R. said:
No, because the ";" marks the end of the variable declaration list. In
the above code, you are indeed creating an implied global variable
called h,

No, it creates, if it succeeds (and does not throw an exception, as observed
in some instances with MSHTML before, and required in ECMAScript Ed. 5
strict mode), a property with that name of the ECMAScript Global object or
overwrites a property with that name of an object in the scope chain.
instead of creating a private variable in the function scope.

The proper terminology here is "_local_ variable", not what you wrote.
Visibility modifiers do not exist in these implementations; privacy can
only be achieved implicitly, through closures. So far there is no closure
in that code regarding those variables.
it is one of the JavaScript best practices to declare all of the
variables used in a function at the top of the function body. You may
have many variables separated by commas, e.g

var el = ...,
h = ...,
w = ...,
i, j, len, ..., z;

You must not use multiple var statements such as:
var el;
var h = ...;
var z;

Wrong. In fact, it turns out that syntactically *correct*, adjacent `var'
statements work better with editors capable of refactoring, such as Eclipse
JSDT. And they help to avoid the problem that you encountered, because it
would likely be a syntax error if you mistyped the semicolon, and automatic
semicolon insertion would take place if you forgot to type the semicolon at
all.


PointedEars
 
C

Cal Who

Denis McMahon said:
Rubbish.

You can use as many var statements as you like. Nothing in the standards
or the implementation prevents this, so "must not" is incorrect.

Some people think all variables should be declared in a single statement.
Some people use a different statement for each type of variable, where
type is the sort of data that it will be used to hold (array, string,
integer, float, object etc).
Some people just use one variable per var.

These are all permitted by the various standards, and they all work.
There is no reason that you "must" or "must not" do any of these.

Also, "best practice" is invariably "in the opinion of the author of the
website / book / blog / whatever" that said example of best practice
appears in. As a matter of interest, what's your reference for "best
practice"? If I write a book or start a blog called "Javascript - Best
Practice" does that make it true?

Rgds

Denis McMahon

Thanks
 
D

Denis McMahon

The advantages of using the Single var Pattern at the top of your
functions are:

I'm not objecting to the suggestion that best practice includes defining
all your variables with var statements at the start of a function. I
agree that this is indeed best practice.

I am, however, objecting to (a) your assertion that it "must" be done, or
(b) that best practice requires the use of a single var statement.

Rgds

Denis McMahon
 
T

Thomas 'PointedEars' Lahn

J.R. said:
"must not" was exaggerated on purpose, because using many var statements
is an antipattern in JavaScript.

In your humble opinion (which may not even be your opinion but that of the
author of some botched book you read instead, and now you think you know the
language and its "best practices").
The advantages of using the Single var Pattern at the top of your
functions are:

You are confusing two concepts here.
- there's a single place to look for all the local variables needed by
the function;

The comma operator does not help with this.
- prevention of logical errors when a variable is used before it’s
defined;

The comma operator does not help with this.
- Helps you remember to declare variables and therefore minimize
globals;

The comma …
- only one var statement means less code to type and a reduction
in the file size.

Sometimes. Because for readable code, you will have to indent the second,
third aso. line. In particular, with the style you used above, you do not
save or add *any* byte. If this is not obvious to you, look more carefully:

var.el.=....,.........
....h =....,..........
....w.=....,..........
....i,.j,.len,....,.z;

vs.

var.el.=....;.........
var.h.=....;..........
var.w.=....;..........
var.i,.j,.len,....,.z;

At any rate, the potential savings are so very small compared to what
trimming comments, minimization and gzipping can achieve that this is not a
convincing argument. Taking my current local object.js as an example:

awk '
BEGIN {
total = 0;
var_lines = 0;
print;
}

/^[[:space:]]*var/ {
total += length();
var_lines++;
}

END {
print "LOCs: " NR;
print "var LOCs: " var_lines;
print "avg(length(var LOCs)): " total/var_lines " bytes";
savings = 2 * var_lines;
print "Potential savings (best case): " savings " bytes (2 * " var_lines
")";
"wc -c " FILENAME | getline wc_out;
split(wc_out, data);
filesize = data[1];
print "File size: " filesize " bytes";
print "Potential savings (best case): " savings/filesize * 100 " %";
}' \
object.js

LOCs: 2009
var LOCs: 66
avg(length(var LOCs)): 27.8788 bytes
Potential savings (best case): 132 bytes (2 * 66)
File size: 55694 bytes
Potential savings (best case): 0.237009 %
----

2 bytes per `var' line because changing

var.foo;\n
var.bar;\n

to

var.foo,\n
..bar;\n

saves two characters on the second, third etc. line per variable
declaration. However, it should be noted that the more readable form is

var\n
..foo,\n
..bar;\n

which saves *nothing* with \n = <LF> but *adds* one byte with \n = <CR><LF>
as it means removing a space [−1] and adding a newline [+1|+2] on the first
line, adding two spaces [+2] on the second line, and removing "var" (3 bytes
[−3]) and adding a space [+1] on the third line).

With tab indentation, it is a change of

var.foo;\n
var.bar;\n

to

var\n
<HT>foo,\n
<HT>bar;\n

which means removing one space [−1] and adding one newline [+1|+2] on the
first line, adding one <HT> [+1] on the second line and saving 3 bytes [−3]
on the second line (a total of only 1 or two 2 saved bytes). (However, tab
indentation may require additional adjustments at the reader's, and is
therefore also not recommended for posting to Usenet.)
There are patterns in any programming language usually adopted by
programmers as "best coding practices". And it happens to other fields
of study too. See <http://en.wikipedia.org/wiki/Best_Coding_Practices>

If you get a bunch of authors (books, blogs, etc.) that state the same
"best practices" in any programming language, then you can bet who is
wrong or right...


No, it doesn't, although I know you're a very experienced and smart
programmer. However, if you published some evidence such as performance
tests, etc., then you could state that some practice should be either
considered a good one or avoided altogether.

Your logic is flawed: <http://en.wikipedia.org/wiki/Ipse_dixit>


PointedEars
 
J

J.R.

No, it creates, if it succeeds (and does not throw an exception, as observed
in some instances with MSHTML before, and required in ECMAScript Ed. 5
strict mode), a property with that name of the ECMAScript Global object or
overwrites a property with that name of an object in the scope chain.

Considering only the given code by Cal, it creates two implied global
variables (w and h), according to ECMA-262 3rd, section 12.2:

"If the variable statement occurs inside a FunctionDeclaration, the
variables are defined with function-local scope in that function, as
described in s10.1.3. Otherwise, they are defined with *global scope*
(that is, they are created as members of the global object, as described
in 10.1.3) [...]"
The proper terminology here is "_local_ variable", not what you wrote.

As written above, the correct terminology is indeed "variable defined in
the function-local scope".
Visibility modifiers do not exist in these implementations; privacy can
only be achieved implicitly, through closures. So far there is no closure
in that code regarding those variables.

ACK, except for the *only*.
Wrong. In fact, it turns out that syntactically *correct*, adjacent `var'
statements work better with editors capable of refactoring, such as Eclipse
JSDT.

It's not wrong, it's a different approach instead. ECMAScript permits
using either a single var or many var statements as one wishes. I prefer
the single var pattern.

And I don't care about Eclipse - I'm talking about JavaScript not JAVA.
Personally, I prefer Python / Django but it doesn't matter to this
discussion anyway.
And they help to avoid the problem that you encountered, because it
would likely be a syntax error if you mistyped the semicolon, and automatic
semicolon insertion would take place if you forgot to type the semicolon at
all.

ACK.
 
J

John G Harris

But I will still ignore you if you (continue to) post with an invalid
From/Reply-To header field value. Usenet can only work if communication ^^^^^^
works both ways.
<snip>

What have e-mail addresses got to do with Usenet communication ?

John
 
J

J.R.

I'm not objecting to the suggestion that best practice includes defining
all your variables with var statements at the start of a function. I
agree that this is indeed best practice.

I am, however, objecting to (a) your assertion that it "must" be done, or
(b) that best practice requires the use of a single var statement.


You are right, I should have not used the "must not" as it expresses
prohibition in English, and a code pattern is not necessarily one of the
"best coding practices", although, in many cases, they seem to walk hand
in hand. And sticking to a strict coding style is usually considered one
of the best practices in many programming languages.

Examples of "best practices" in JS:
<http://dev.opera.com/articles/view/javascript-best-practices/>

The above link is propped up by the Mozilla Developer Network
<https://developer.mozilla.org/en-US/learn/javascript>, and there are
other pages at MDN concerning to best practices in other aspects of
development (extensions, security, ect.).

Cheers,
Joao Rodrigues (J.R.)
 

Ask a Question

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

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

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top