在新操作员上缺少这个

时间:2013-03-04 13:30:14

标签: javascript ajax new-operator

我在AJAX调用返回时错过了这个。

interar.js

interar.Remoter = function (data) {
  this.server = data.server;
  this.init(data);
};

interar.Remoter.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB;
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        this.uuid = result.uuid;
        console.log("UUID v4 From Server " +  this.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

的index.html

var W = new interar.Remoter("mydata");

返回 succeedCB 时, 窗口 不是 interar 实例

2 个答案:

答案 0 :(得分:1)

在初始化实例时缓存this

interar.Remoter.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB, self = this;
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        self.uuid = result.uuid;
        console.log("UUID v4 From Server " +  self.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

此外,您可能希望设置prototype.init Remoter而不是Remote

答案 1 :(得分:0)

应该是

interar.Remote.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB;
    var self = this; <-- Assign this to a variable for closure bases access
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        self.uuid = result.uuid;
        console.log("UUID v4 From Server " +  self.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

当您将succeedCB作为回调传递时,succeedCB执行的上下文将不会知道this实例。

因此,我们可以使用闭包在this

中访问succeedCB