“沙箱”用于使用javascript库的多个实例

时间:2014-10-08 08:01:28

标签: javascript node.js

我正在使用js lib,它将创建一个全局变量" AV"在WebApp中随处使用。 但是我想在一个WebApp中创建一个"沙箱"(实际上不是一个严格的沙箱,因为没有安全的顾虑)在一个WebApp中使用多个不同的" AV"。

我在下面为浏览器编写了一个包装,它可以工作。

var AVContexts = {
    App1: null,
    App2: null
}

var ContextLoader = function (appId, appKey) {
    this.AV = null;
    this.runInThis = function (script) {
        eval(this.script);
        this.AV.initialize(appId, appKey);
    }
    this.loadContext = function (appId, appKey) {
        $.ajax({
            url: 'js/av.js',
            dataType: "text",
            context: this
        }).done(function (data) {
            this.script = data;
            this.runInThis.call(this);
        }).fail(function () {
            console.log('failed');
        });
    }
    this.loadContext(appId, appKey);
}

AVContexts.App1 = new ContextLoader(
        "[appid]",
        "[appkey]"
);
AVContexts.App2 = new ContextLoader(
        "[appid]",
        "[appkey]"
);

// Do something
var TestObject = AVContexts.App1.AV.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}, {
                success: function (object) {
                    alert("AVOS Cloud works!");
                }
            });

但是当我把它移到nodejs时。

发生错误
this.runInThis.call(this);

ERROR: Cannot call method 'call' of undefined

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您应该缓存" this",如下所示:

var me = this;

在使用$ .ajax之前。然后,

$.ajax().done(function() {
    me.runInThis.call();
});

如果你想知道原因,

运行

console.log(this); 

之前

this.runInThis.call(this);

你会知道原因。