在另一个对象的方法中使用一个对象的方法时,如何获得我想要的上下文?
How do I gain the context I want when using a method from an object in a method of another object?
第一个对象和方法:
objectOne.prototype.getData = function (id, callback) {
this._sendRestRequest({
method: "GET",
path: /accounts/ + id + "/data"
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
console.error("[ERROR]", statusCode + " Error: " + body.message + " (error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.trades) {
callback(null, body.trades);
} else {
callback("Unexpected response");
}
});
};
第二个对象和方法:
function dataManip = function () {
this.data;
this.getData = function () {
if(some condition) {
objectOne.getData("31313", function (error, data) {
this.data = data;
});
}
如果我要 console.log this.data 它将是未定义的,因为 this 指的是第一个对象而不是第二个对象。
所以我一直在尝试应用、绑定和调用;但是,我似乎无法让它工作,因此 "this" 指的是 dataManip 而不是 ObjectOne。获得我需要的上下文的最佳方式是什么?
编辑:使用绑定、应用和调用会导致错误,因为在第一个对象中使用了 "this"。
你可以设置this
回调,像这样
objectOne.getData("31313", function (error, data) {
this.data = data;
}.bind(this));
第一个对象和方法:
objectOne.prototype.getData = function (id, callback) {
this._sendRestRequest({
method: "GET",
path: /accounts/ + id + "/data"
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
console.error("[ERROR]", statusCode + " Error: " + body.message + " (error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.trades) {
callback(null, body.trades);
} else {
callback("Unexpected response");
}
});
};
第二个对象和方法:
function dataManip = function () {
this.data;
this.getData = function () {
if(some condition) {
objectOne.getData("31313", function (error, data) {
this.data = data;
});
}
如果我要 console.log this.data 它将是未定义的,因为 this 指的是第一个对象而不是第二个对象。
所以我一直在尝试应用、绑定和调用;但是,我似乎无法让它工作,因此 "this" 指的是 dataManip 而不是 ObjectOne。获得我需要的上下文的最佳方式是什么?
编辑:使用绑定、应用和调用会导致错误,因为在第一个对象中使用了 "this"。
你可以设置this
回调,像这样
objectOne.getData("31313", function (error, data) {
this.data = data;
}.bind(this));