Duplicate Definition in JavaScript.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    Duplicate Definition in JavaScript.

    Today i encountered a typical thing. So far what i knew that JavaScript had a scope inside a function but it was not there. I think in newer version of JavaScript it is introduced, in older version there may be. Anyway .....
    Have a look at my code snippet ....

    [code=javascript]
    function test(){
    var s = "Hello!";
    var s = "Hi!";
    alert(s); //it alerts the latest value of s, and here is no duplicate definition of s
    }
    [/code]

    [code=javascript]
    function test(){
    //some code
    }

    function test(){
    //some latest code
    }
    [/code]

    Whenever i call test it executes the latest code, here is also not duplicate definition. How JavaScript handles it?
    Please explain.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    with you first example you REdeclare var s within the function ... when you set the javascript-engine to handle the interpretation of the code in strict-mode in firefox/mozilla then the error console will show you that as a warning.

    the second is OVERwriting ... basically functions are declared in the window-scope and there you overwrite the first with the second ... basically what you do is:

    [CODE=javascript]this.test = function() {
    // some code
    }
    [/CODE]
    where this is the window-object's scope ...

    kind regards

    Comment

    • rnd me
      Recognized Expert Contributor
      • Jun 2007
      • 427

      #3
      scope is only preserved and layered in functions:
      Code:
      function test(){
        function test(){
          return test;
        }
       return test;
      }

      tests:

      test().toString () // =
      Code:
      function test() {
          return test;
      }
      test.toString() // =
      Code:
      function test() {
      
          function test() {
              return test;
          }
      
          return test;
      }

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        ahh ... and to put FF into strict-mode ... type in the address-bar: about:config there a filter appears and you type in the filter: javascript.opti ons.strict ... set its value to true -> see what a bunch of errors and information you now get in the console additionally :)

        kind regards

        Comment

        Working...