javascript Nodejs 从函数内部调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13768764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nodejs calling function from within a function
提问by Sleiman Jneidi
I have 3 methods
我有3种方法
exports.getImageById = function (resultFn, id) {
...
}
exports.getCollectionById = function (resultFn, id) {
}
in the third method I want to call both methods
在第三种方法中,我想同时调用这两种方法
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);
}
I can call first function this.getCollectionById
but it fails to call this.getImageById
, it says undefined function, whats the reason for that?
我可以调用第一个函数,this.getCollectionById
但调用失败this.getImageById
,它说未定义的函数,这是什么原因?
回答by Juan Mendes
When you call this.getCollectionById
passing it a callback, the callback doesn't have access to the same this
当您调用this.getCollectionById
传递它回调时,回调无法访问相同的this
The simplest solution is to save this
as a local variable.
最简单的解决方案是保存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);
}
回答by bfavaretto
The value of this
inside the inner function is not the same object as outside, because it's determined depending on how the function is called. You can find a detailed explanation in the MDN article on this
.
this
内部函数内部的值与外部的对象不同,因为它取决于函数的调用方式。您可以在MDN 文章中this
找到详细说明。
One of the ways to solve it is by keeping a reference to the outer this
in another variable such as that
:
解决它的方法之一是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
);