0

我通过动态创建脚本标签来加载js,我已经在脚本加载时编写了一个回调函数,但是当在加载js后调用函数时,当我在firebug中检查它时,我无法访问我的对象属性值不见了。下面是我的代码,请回答我的代码中有什么问题,或者是否有不同的方法来做同样的事情。

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();
4

2 回答 2

2

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

不将上下文 ( obj) 传递给show函数。你需要做一个像

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

或者如果您的目标浏览器支持它,请使用绑定:

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

大多数 JS 框架也包含bind或类似的功能。

于 2011-11-23T11:10:58.367 回答
1

问题是this动态范围。我认为这应该有效:

oScript.onload = function () {obj.show()};
于 2011-11-23T11:11:28.210 回答