简体   繁体   English

使用_this引用父类方法

[英]Using _this to refer to parent class method

I'm using the prefix _this to refer to a parent class function when calling it from a callback function. 从回调函数调用它时,我使用前缀_this来引用父类函数。 However, when I run the node server I get the error message '_this is not defined'. 但是,当我运行节点服务器时,出现错误消息“ _this is not defined”。 I've actually pulled this code directly from a MEAN stack book I'm learning from but I can't seem to get around this. 实际上,我实际上是从我正在学习的MEAN堆栈书中直接提取了此代码,但似乎无法解决这个问题。

Parent Function 父功能

var getErrorMessage = function(err){
var message = '';
if(err.code){
    switch(err.code){
        case 11000:
        case 11001:
        message = 'Username already exists';
        break;
        default:
        message = 'Something went Wrong';
    }
} else{
    for(var errName in err.errors){
        if(err.errors[errName].message){
            message = err.errors[errName].message;
        }
    }
}

return message;
};

Function being called in a callback later on 稍后在回调中调用该函数

exports.saveOAuthUserProfile = function(req, profile, done){
User.findOne({provider: profile.provider, providerId: profile.providerId}, function(err,user){
    if(err){
        return done(err);
    } else{
        if(!user){
            var possibleUsername = profile.username || ((profile.email) ? profile.email.split('@')[0] : '');

            User.findUniqueUsername(possibleUsername, null, function(availableUsername){
                profile.username = availableUsername;

                user = new User(profile);

                user.save(function(err){
                    if(err){
                        var message = _this.getErrorMessage(err);
                        req.flash('error',message);

                        return res.redirect('/signup');
                    } else{
                        return done(err,user);
                    }
                });
            });
        } else{
            return done(err, user);
        }
    }
});
};

In continuation with the comment 继续评论

Declare as below after the parent function in global scope. 在全局范围内的父函数之后声明如下。

var _this = {};
_this.getErrorMessage = getErrorMessage; // Passing the function reference

Later in callback 稍后在回调中

_this.getErrorMessage(/*YOUR_PARAMETERS_HERE*/);

Alternatively you can remove _this completely and call the function directly as the parent function is in global scope. 或者,您可以完全删除_this并直接调用该函数,因为父函数在全局范围内。

Note: the understanding is Both the parent function and callback is in the same .js file with parent function declared on global scope with respect to that .js file and not declared as GLOBAL.getErrorMessage which makes it explicitly global as window object in client side. 注意:理解是父函数和回调都在同一个.js文件中,父函数相对于该.js文件在全局范围内声明,而不是声明为GLOBAL.getErrorMessage ,这使其在客户端作为window对象显式地全局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM