0

我在 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});
};

索引.html

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

succeedCB返回时,this is window not interar instance

4

2 回答 2

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.initofRemoter而不是Remote.

于 2013-03-04T13:47:18.950 回答
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

于 2013-03-04T13:47:34.070 回答