javascript - Node JS 中的内部类函数使用抛出错误

标签 javascript node.js oop express

我正在学习 Node JS,我正在学习如何在 Node 中创建 OOP 结构。我有一个简单的类,我在其中使用函数在数据库中检查和创建用户。当我在函数内部调用类函数时出现 TypeError。我的类(class)代码,

var method = AccessRegisterAction.prototype;

function AccessRegisterAction(parameters) {

    this._bcrypt = require('bcrypt-nodejs');
    this._cassandra = require('cassandra-driver');
    this._async = require('async');


    this._uname = parameters.uname;
    this._email = parameters.email;
    this._passwd = parameters.passwd;

    //Connect to the cluster
    this._client = new this._cassandra.Client({contactPoints: ['127.0.0.1'], keyspace: 'testdb'});

    //this._bcrypt.hashSync("bacon");

}

/*
 * This method "createUser" is used to create new users
 *
 * First it will check for user's email is in database or not.
 *
 * If email is registered we will process accordingly,
 * else we will process accordingly.
 *
 * */

method.createUser = function () {
    var selectUserFromDBQuery = "SELECT uid from testdb.users WHERE email = '?' ALLOW FILTERING";

    this._client.execute(selectUserFromDBQuery, this._email, function (err, result) {

        //if there is not any error while fetching data
        if (!err) {

            //if there is result, it means we have email already registered
            if (result.rows.length > 0) {

                //so now we need to show user is already registered error
                //to the user
                this.errorWhileCreatingAccount(2);

            } else {

                //here we are checking user's username because
                //we have not found user's email in database and we
                //are good to go to register user
                this.userNameCheck();


            }
        }
        else {
            this.errorWhileCreatingAccount(1);
        }

    });
};


/*
 * This method will check for username in database.
 *
 * If there is username registered in database than we will
 * show error that username is taken otherwise
 * we will process to register user.
 * */
method.userNameCheck = function () {
    var checkUserNameQuery = "SELECT uid from testdb.users WHERE uname = '?' ALLOW FILTERING";

    this._client.execute(checkUserNameQuery, this._uname, function (err, result) {

        //if there is not any error while fetching data
        if (!err) {

            //if there is result, it means we have email already registered
            if (result.rows.length > 0) {

                //so username is taken and we need to tell user to
                //use different username
                this.errorWhileCreatingAccount(3);

            } else {

                //here we are registering user and adding information into database
                this.newUserCreate();

            }
        }
        else {
            this.errorWhileCreatingAccount(1);
        }

    });

};

/*
 * This method will create new user into database
 *
 * Simple as that
 * */
method.newUserCreate = function () {
};


/*
 * This function will throw an error which was occurred during the account creation process
 * */
method.errorWhileCreatingAccount = function (errorCode) {
    var _error = {error: "", msg: ""};

    switch (errorCode) {
        case 1:
            _error.error = true;
            _error.msg = "There was error while checking your information. Please try again.";
            break;
        case 2:
            _error.error = true;
            _error.msg = "You have already created account with this email. " +
                "Please use forgot password link if you don't remember your login details.";
            break;
        case 3:
            _error.error = true;
            _error.msg = "Username that you chose is already taken. Please try different username.";
            break;
        default:
            _error.error = true;
            _error.msg = "There was error an error. Please try again.";
            break
    }

};


// export the class
module.exports = AccessRegisterAction;

我得到的错误信息是,

events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: this.userNameCheck is not a function
    at /Users/user/Desktop/Projects/nodejs/testproject/application/classes/UserAccessAction/AccessRegisterAction.js:55:22
    at next (/Users/user/node_modules/cassandra-driver/lib/utils.js:616:14)
    at readCallback (/Users/user/node_modules/cassandra-driver/lib/request-handler.js:202:5)
    at Connection.invokeCallback (/Users/user/node_modules/cassandra-driver/lib/connection.js:584:5)
    at Connection.handleResult (/Users/user/node_modules/cassandra-driver/lib/connection.js:522:8)
    at emitThree (events.js:116:13)
    at ResultEmitter.emit (events.js:194:7)
    at ResultEmitter.each (/Users/user/node_modules/cassandra-driver/lib/streams.js:482:17)
    at ResultEmitter._write (/Users/user/node_modules/cassandra-driver/lib/streams.js:466:10)
    at doWrite (_stream_writable.js:307:12)

我调用这个函数的代码是,

var param = {uname: "testname", email: "fake@test.com", passwd: "test123"};
    var AccessRegisterAction = require('../application/classes/UserAccessAction/AccessRegisterAction');
    var register = new AccessRegisterAction(param);
    register.createUser();

谁能告诉我我的错误在哪里?如何将 oop 与 nodejs 结合使用?

谢谢

最佳答案

因为看起来你使用的是 ES5 风格,所以我不推荐箭头函数。但是,正如评论中指出的那样,this 的值在每个 function 语句中发生变化。因此,在进入内部函数之前,您需要保存要使用的上下文。例如:

method.createUser = function () {
    var context = this;
    var selectUserFromDBQuery = "SELECT uid from testdb.users WHERE email = '?' ALLOW FILTERING";

    this._client.execute(selectUserFromDBQuery, this._email, function (err, result) {

    //if there is not any error while fetching data
    if (!err) {

        //if there is result, it means we have email already registered
        if (result.rows.length > 0) {

            //so now we need to show user is already registered error
            //to the user
            context.errorWhileCreatingAccount(2);

        } else {

            //here we are checking user's username because
            //we have not found user's email in database and we
            //are good to go to register user
            context.userNameCheck();


        }
    }
    else {
            context.errorWhileCreatingAccount(1);
        }

    });
};

在尝试从新函数中调用 this 的每个方法中执行此操作。

关于javascript - Node JS 中的内部类函数使用抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280028/

相关文章:

javascript - 邮政信箱正则表达式在包含单词 "box"的地址上失败

java - 子类可以与其父类关联吗?

php - 我如何能够在 Php 中执行以下操作,它不会抛出任何错误,请解释

javascript - appendChild()在我的YouTube chrome扩展程序中不起作用

c# - 删除脚本错误弹出窗口

node.js - jdk、node、webdriver升级后无法启动webdriver-manager

javascript - 如何在 Node.JS 中向响应对象添加自定义函数

javascript - Node.js 请求中的 JSON 和数据有什么区别?

php - Lumen中 '$app->run()'的实现在哪里?

javascript - 使用 ng-hide 不显示 Angular 模板