What about the 'this' keyword when used in a gloabl object?
Say, for example, we have:
var SomeGlobalObject = { rendered: true, show: function() { if(this.rendered) alert("hello"); } }
Now, if we call the inline script on the HTML page:
SomeGlobalObject.show(); window.setTimeout("Msg.show()", 1000);
everything is working fine.
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.
- Do you know why this is happening?
- Could you please explain if there is another smarter way to do this without rewriting "SomeGlobalObject.someProperty" each time into SomeGlobalObject code?
Thanks!
AppendEvent is just a cross-browser function for adding events, the code is below, but it doesnβt matter 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); }