0

私は3つの方法を持っています

exports.getImageById = function (resultFn, id) {
 ...
}

exports.getCollectionById = function (resultFn, id) {
}

3番目のメソッドでは、両方のメソッドを呼び出したい

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、未定義の関数と表示されます。その理由は何ですか?

4

2 に答える 2

4

コールバックを渡して呼び出す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);
}
于 2012-12-07T18:21:08.163 に答える
2

内部関数の内部の値はthis、関数の呼び出し方法によって決まるため、外部と同じオブジェクトではありません。のMDN 記事でthis詳細な説明を見つけることができます。

thisそれを解決する方法の 1 つは、次のような別の変数でアウターへの参照を保持することです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
);
于 2012-12-07T18:21:24.007 に答える