【发布时间】:2010-11-14 06:04:25
【问题描述】:
我正在实现一个基于 jquery 的 getscript 的按需脚本控制器,它看起来像这样:
function controller = function(){
var script = function(){
var scripts = {};
return {
load: function(jsurl){
$.getScript(jsurl, null);
},
run: function(js){
window[js].apply(this,null);
}
}
};
return {
script: script()
};
}
var ctlr = controller();
那么这里是一个远程脚本,其中包含一个要加载的函数——remote.js
function remotefunc(){
alert( 'remotefunc invoked' );
}
在主脚本中,这是整个事情应该如何工作的:
ctlr.script.load( 'remote.js' ); // remote script successfully loaded
ctlr.script.run( 'remotefunc' ); // got an error, window['remotefunc'] undefined
但正如您所见,“remotefunc”是在全局“窗口”范围内定义的,因此窗口对象应该能够“看到”它。
我认为问题可能是“控制器”定义中的闭包,所以我直接 $.getScirpt 不使用“控制器”:
$.getScript( 'http://path/to/remote.js', function(){
window['remotefunc'].apply( this, null ); // this worked
} );
奇怪。所以它是关于“控制器”的实现(我需要它)!有人可以帮我解决这个问题吗?如何修复“控制器”实现,以便
window[js].apply(this,null);
真的可以吗?
谢谢。
【问题讨论】:
标签: javascript jquery scope closures