In jQuery's core the *local* variable window is being set. You're
trying to rewrite the global variable 'window' that already exists.
You can only set a var named 'window' in a scope that is not the
global one, like this:

function giveMeChocolate(){
 var window = this;
 //this == the global window object
 window.alert('hmm');
}

Your example rewritten (notice that it's all encapsulated in an
anonymous function, like jQuery):

<html>
<head><title>this example</title>
<scripttype="text/javascript">
(function(){
  var window=this;
  function dosomething(){
      this.style.color="red";
  };
  window.onload=function(){
    document.getElementById("h").onclick=dosomething;
  };
})();
</script>
</head>
<body>
<hl id="h">this example</h1>
</body>
</html>

The reason this is done is that the Javascript engine will search for
variables "from the inside out". See this:

one = 1;

function a(){

  function b(){
     alert(one);
     // first it will check if there is a local var named 'one',
     // if not, it looks for it in the next scope

     // now we'll define a *local* var also named 'one'
     // with a different value
     var one = 2;
     alert(one);
   };
   b();

   alert(one);
   // here 'one' is the global var, there is no 'one' in
   // the current scope

  // and now we define another local var
  // in this function's scope
  var one = 3;
  alert(one);
};

a();

// notice the value of the global 'one' is unchanged
alert(one);

Hope that's clear!

- ricardo

On Feb 26, 6:27 am, tkinter <yangbeyonds...@gmail.com> wrote:
> I write a code like below to use "window=this", but it is wrong!!
>
> <html>
> <head><title>this example</title>
> <script language="Javascript" type="text/javascript">
> window=this;
> function dosomething(){
>         this.style.color="red";
>         }
>
>         window.onload=function(){ document.getElementById
> ("h").onclick=dosomething; }
> </script>
> </head>
>
> <body>
> <hl id="h">this example</h1>
> </body>
> </html>
>
> the right code is cancel the "window=this", why? why use the
> "window=this" in jquery source code???

Reply via email to