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

Discussion in 'Javascript' started by Cal Who, Nov 13, 2011.

  1. Cal Who

    Cal Who Guest

    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)
     
    Cal Who, Nov 13, 2011
    #1
    1. Advertisements

  2. 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
     
    Thomas 'PointedEars' Lahn, Nov 13, 2011
    #2
    1. Advertisements

  3. Cal Who

    Cal Who Guest

    Also, I should have included the "..." that (I just added) to make cleared
    that there was more code.
    I don't have the backgroung to understand the above paragraph.
    Is the first approch (var w = document.getElementById(obj).offsetWidth) the
    better one?
    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.
    Good catch but I'm still developing " findPosAndSize"


    Thanks
     
    Cal Who, Nov 13, 2011
    #3
  4. 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.
    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.
    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.
    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
     
    Thomas 'PointedEars' Lahn, Nov 13, 2011
    #4
  5. Cal Who

    Cal Who Guest

    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
     
    Cal Who, Nov 13, 2011
    #5
  6. Cal Who

    J.R. Guest

    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.R., Nov 13, 2011
    #6
  7. Cal Who

    J.R. Guest

    Correcting a typo:

    var el = (typeof obj == 'string') ? document.getElementById(obj) :
    obj,
    w = el.offsetWidth, // , instead of ;
    h = el.offsetHeight;
     
    J.R., Nov 13, 2011
    #7
  8. Cal Who

    Cal Who Guest

    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;
    ...
     
    Cal Who, Nov 13, 2011
    #8
  9. Cal Who

    J.R. Guest

    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;
     
    J.R., Nov 13, 2011
    #9
  10. Cal Who

    Cal Who Guest


    Thanks a lot
     
    Cal Who, Nov 14, 2011
    #10
  11. 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
     
    Denis McMahon, Nov 14, 2011
    #11
  12. Cal Who

    J.R. Guest

    "must not" was exaggerated on purpose, because using many var statements
    is an antipattern in JavaScript.
    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.

    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.
     
    J.R., Nov 14, 2011
    #12
  13. You mean _Outlook_ Express, as it says in the `X-Newsreader' header field of
    your postings [1].
    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/>
     
    Thomas 'PointedEars' Lahn, Nov 14, 2011
    #13
  14. 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.
    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.
    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
     
    Thomas 'PointedEars' Lahn, Nov 14, 2011
    #14
  15. Cal Who

    Cal Who Guest

    Thanks
     
    Cal Who, Nov 14, 2011
    #15
  16. 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
     
    Denis McMahon, Nov 14, 2011
    #16
  17. 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").
    You are confusing two concepts here.
    The comma operator does not help with this.
    The comma operator does not help with this.
    The comma …
    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.)
    Your logic is flawed: <http://en.wikipedia.org/wiki/Ipse_dixit>


    PointedEars
     
    Thomas 'PointedEars' Lahn, Nov 14, 2011
    #17
  18. Cal Who

    J.R. Guest

    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) [...]"
    As written above, the correct terminology is indeed "variable defined in
    the function-local scope".
    ACK, except for the *only*.
    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.
    ACK.
     
    J.R., Nov 14, 2011
    #18
  19. <snip>

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

    John
     
    John G Harris, Nov 14, 2011
    #19
  20. Cal Who

    J.R. Guest


    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.)
     
    J.R., Nov 14, 2011
    #20
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.