我在AJAX调用返回时错过了这个。
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});
};
var W = new interar.Remoter("mydata");
返回 succeedCB 时, 窗口 不是 interar 实例
答案 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