我有3种方法
exports.getImageById = function (resultFn, id) {
...
}
exports.getCollectionById = function (resultFn, id) {
}
在第三种方法中我想调用两种方法
exports.getCollectionImages = function (resultFn, collectionId) {
var arr = new Array();
this.getCollectionById( // fine, 1st call
function (result) {
var images = result.image;
for (i = 0; i < images.length; i++) {
this.getImageById(function (result1) { // error, 2nd call
arr[i] = result1;
}, images[i]
);
}
}
, collectionId
);
resultFn(arr);
}
我可以调用第一个函数this.getCollectionById
,但它无法调用this.getImageById
,它表示未定义的函数,是什么原因?
答案 0 :(得分:2)
当您致电this.getCollectionById
向其传递回调时,回调无法访问相同的this
最简单的解决方案是将this
保存为局部变量。
exports.getCollectionImages = function (resultFn, collectionId) {
var arr = new Array();
var me = this; // Save this
this.getCollectionById( // fine, 1st call
function (result) {
var images = result.image;
for (var i = 0; i < images.length; i++) {
// Use me instead of this
me.getImageById(function (result1) { // error, 2nd call
arr[i] = result1;
}, images[i]);
}
}, collectionId);
resultFn(arr);
}
答案 1 :(得分:2)
内部函数中this
的值与外部不是同一个对象,因为它取决于函数的调用方式。您可以在MDN article on this
。
解决问题的方法之一是在另一个变量(例如this
)中保留对外that
的引用:
var that = this;
this.getCollectionById( // fine, 1st call
function (result) {
var images = result.image;
for (i = 0; i < images.length; i++) {
that.getImageById(function (result1) { // 2nd call
arr[i] = result1;
}, images[i]
);
}
}
, collectionId
);