我通过动态创建脚本标签来加载js,我在脚本加载时编写了一个回调函数,但是当加载js后调用函数时,当我 checkin 它时,我无法访问我的对象属性 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();
最佳答案
这个
oScript.onload = obj.show;//most browsers
不将上下文 (obj
) 传递给 show
函数。你需要像这样关闭
oScript.onload = function() { obj.show() }
或使用bind如果您的目标浏览器支持它:
oScript.onload = obj.show.bind(obj)
大多数 JS 框架还包含 bind
或类似的函数。
关于javascript - 在 javascript 回调函数中未获取现有对象属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8241136/