why skipping "this" in this.value will work sometimes and sometimes not

Discussion in 'JavaScript' started by winterheat, Aug 20, 2008.

  1. #1
    The following code is on http://www.0011.com/test_js/test_without_this.html

    the first input field uses alert(value) instead of alert(this.value) and it works.

    the second and third input fields do not use the "inline anonymous function" but use another anonymous function... but the second one will show the value while the third one won't. I thought inline anonymous function is the same as assigning element.onclick= function() { whatever there was } isn't it? If so why would the first input field work and the third doesn't? It is true in IE 7, Firefox 3, and Safari 3. Many thanks!

    <form>
    
    <input id="text1" type="text" value="wah ha ha 1" onclick="alert(value)">
    <input id="text2" type="text" value="wah ha ha 2">
    <input id="text3" type="text" value="wah ha ha 3">
    
    </form>
    
    <script>
    
    document.getElementById("text2").onclick = function() { alert(this.value) }
    document.getElementById("text3").onclick = function() { alert(value) }
    
    </script>
    HTML:
     
    winterheat, Aug 20, 2008 IP
  2. SearchBliss

    SearchBliss Well-Known Member

    Messages:
    1,899
    Likes Received:
    70
    Best Answers:
    2
    Trophy Points:
    195
    Digital Goods:
    1
    #2
    Go with what works and don't waste your time with the rest...or complicate things more by using document.form as well. :)
     
    SearchBliss, Aug 20, 2008 IP
  3. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The last one won't work cause it uses value from the global scope, not the value of the unput field. When creating an anonymous function you should always use this to make sure that the right object is used. Not using this will cause looking for the variable in the global scope as if you have used window.value.
     
    xlcho, Aug 21, 2008 IP
  4. Stomme poes

    Stomme poes Peon

    Messages:
    3,195
    Likes Received:
    136
    Best Answers:
    0
    Trophy Points:
    0
    #4
    And it's generally good form with JS to avoid or reduce confusion with global variables.

    I'd rather set all my variables in functions, and then use window.whatever when I need to use a variable in multiple functions. Global variables weren't ever good ideas-- esp when you're combining multiple javascripts on a single page and they happen to use the same variable names for different things!

    You might want to check out Crackford's book: "Javascript: the good parts".
     
    Stomme poes, Aug 22, 2008 IP