0

When I coded like below, variable 'name' does not have a initial value "test". This is working fine when I do not use "window.onload".

Is there any difference for javascript variables between with "window.onload" and without it

<!DOCTYPE html>
  <html>
      <head>
      <title>HTML5, CSS3 and JavaScript demo</title>
      </head>
      <body>
      <!-- Start your code here -->

     <script>

     window.onload=function(){ 
     var name = "test";

     function foo(msg,msg2) {

              console.log(msg + '  ' + msg2);

              alert(this.name);

  }

  foo('normal call','default');

  var obj = {
              name : 'steve'
          }

  foo.call(obj,'call function','object'); 
  foo.apply(obj,['apply function','object']); 

   }


  </script>
  <!-- End your code here -->
  </body>
  </html>
jongchul
  • 77
  • 5

1 Answers1

0

This is working fine when I do not use "window.onload".

That's because when you're not putting that code in a function, you're declaring name at global scope, making it a global variable, and so you can access it as a property on the global object. In loose mode, when you call foo directly as in your first example, this inside foo will refer to the global object. And so outside the function, it works, because name is global.

Inside, it's just a normal variable, and there's no connection between that variable and any object you can get a reference to in your code.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639