使用jQuery加载脚本时保持范围 [英] Maintain scope when loading script with jQuery

查看:55
本文介绍了使用jQuery加载脚本时保持范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个'test.js'文件,内容如下:

Say I have a file 'test.js' with the following contents:

var test = 'something';

然后我有一个主脚本,需要加载test.js来获取测试变量。

Then I have a primary script that needs to load up test.js to grab the test variable.

显然这有效:

$.ajax({dataType: "script", cache: true, url: 'test.js'});

问题是变量 test 存在在全球范围内。我很好奇是否有办法将它添加到对象中并使其远离全局范围。

The issue is that the variable test exists in the global scope. I'm curious if there's a way to add it into an object and keep it out of the global scope.

类似于:

function scriptloader() {
    this.grabscript = function() {
        return $.ajax({dataType: "script", cache: true, url: 'test.js'});
    }
}

var myloader = new scriptloader();

myloader.grabscript();

理想情况下myloader将包含加载的变量 test 。但是,我可以使用console.log(测试)并仍然看到'某事'。

Where ideally myloader would contain the loaded variable test. However, I can console.log(test) and still see 'something'.

有没有办法将加载的脚本锁定到范围内或者我在做什么?

Is there a way to lock the loaded script into scope or am I dreaming?

推荐答案

您可以尝试这样的事情:

You could try something like this:

function scriptloader() {
  this.grabscript = function() {
    var loader = this;
    $.ajax('test.js', {
      complete: function(response) {
        var js = '(function() {' + response.responseText + ' loader.test = test; })();'
        eval(js);
      },
      dataType: 'text'
    });
  }
}

scriptloader instance然后会获得一个名为 test 的属性。

The scriptloader instance would then get a property called test.

这篇关于使用jQuery加载脚本时保持范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆