javascript using 'this' in global object

Posted by Marco Demaio on Stack Overflow See other posts from Stack Overflow or by Marco Demaio
Published on 2010-03-30T13:35:50Z Indexed on 2010/03/30 13:43 UTC
Read the original article Hit count: 528

What does 'this' keyword refer to when used in gloabl object?

Let's say for instance we have:

  var SomeGlobalObject =
  {
     rendered: true,
     show: function()
     {
        /*
        I should use 'SomeGlobalObject.rendered' below, otherwise it 
        won't work when called from event scope.
        But it works when called from timer scope!!
        How can this be?
        */
        if(this.rendered)
           alert("hello");
     }
  }

Now if we call in an inline script in the HTML page:

SomeGlobalObject.show();
window.setTimeout("Msg.show()", 1000);

everything work ok.

But if we do something like

AppendEvent(window, 'load', Msg.show);

we get an error because this.rendered is undefined when called from the event scope.

  1. Do you know why this happens?
  2. Could you explain then if there is another smarter way to do this without having to rewrite every time "SomeGlobalObject.someProperty" into the the SomeGlobalObject code?

Thanks!

AppendEvent is just a simple cross-browser function to append an event, code below, but it does not matter in order to answer the above questions.

  function AppendEvent(html_element, event_name, event_function)
  {
        if(html_element.attachEvent) //IE
           return html_element.attachEvent("on" + event_name, event_function);
        else
           if(html_element.addEventListener) //FF
              html_element.addEventListener(event_name, event_function, false);
  }

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events