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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:43:54  来源:igfitidea点击:

Nodejs calling function from within a function

javascriptnode.jsfunction

提问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.getCollectionByIdbut 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.getCollectionByIdpassing it a callback, the callback doesn't have access to the same this

当您调用this.getCollectionById传递它回调时,回调无法访问相同的this

The simplest solution is to save thisas 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 thisinside 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 thisin 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
);