0

I'm loading js by creating script tag on the fly, I have written a callback function on script load, but when functions get called after js get loaded, I can't access my object property, when I checked it in firebug the value is missing. Below is my code please answer what is the problem in my code, or is there a different method for doing the same.

obj = {
     cont: null,    
     create:function(){
       this.cont = document.createElement('iframe');
       this.cont.style.setProperty('background-color', '#FFFFFF', 'important');
       this.getJs();
     },

getJs:function(){
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = 'myjs.js';

    oScript.onload = obj.show;//most browsers

    oScript.onreadystatechange = function() {// IE 6 & 7
        if (this.readyState == 'complete') {
            obj.show();
        }
    }
    oHead.appendChild(oScript);        
},

show:function(){
    alert(this.cont);//this.cont is not available when js load and show function get called as a
}   }obj.create();
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34
  • You can set the scope of the event function. See this question http://stackoverflow.com/questions/183214/javascript-callback-scope – PiTheNumber Nov 23 '11 at 11:21

2 Answers2

2

This

   oScript.onload = obj.show;//most browsers

doesn't pass the context (obj) to the show function. You need to make a closure like

   oScript.onload = function() { obj.show() }

or use bind if your target browser supports it:

   oScript.onload = obj.show.bind(obj)

Most JS frameworks also include bind or a similar function.

georg
  • 211,518
  • 52
  • 313
  • 390
  • Thank you for your answer, it is working with "oScript.onload = function() { obj.show() }" but It is not working when I use this.show() instead of obj.show() why is it so? – Pankaj Khairnar Nov 23 '11 at 11:23
  • 1
    Basically, when you use a function as an event listener, `this` gets dynamically bound to `window` when the function is called. So in the function containing `this.show()`, this is actually `window` rather than `obj`. – Tikhon Jelvis Nov 23 '11 at 11:26
1

The issue is that this is dynamically scoped. I think this should work:

oScript.onload = function () {obj.show()};
Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214