My app structure:

我的app结构:

| my-application
| -- app.js
| -- node_modules
| -- public
| -- models
     | -- users.js
| -- routes
     | -- index.js
| -- views
     | -- index.ejs

users.js

function User(name){
   this.name = name;
}

User.prototype.getName = function () {
   return this.name;
};

exports.checkName = function (name) {
   if(name === 'johnSnow'){
      return true;
   }
   return false;
};

module.exports = User;

And i try this:

我试试这个:

index.js

var user  = require('../models/users');

if( user.checkName('dinar') === true ){
    var User = new user('name');
    console.log(User.getName());
}

TypeError: user.checkName is not a function

TypeError:user.checkName不是函数

Is it possible to use functions and constructor function from same module?

是否可以使用同一模块中的函数和构造函数?

Is there any way to do this?

有没有办法做到这一点?

I'm new in node js.

我是节点js的新手。

Thanks in Advance.

提前致谢。

3 个解决方案

#1


0

Yes, it's possible, by putting the normal function as a "static" method on the constructor function itself. In your attempt, you were overwriting the exports object with User so the checkName was lost. Instead, do

是的,通过将普通函数作为“静态”方法放在构造函数本身上是可能的。在您的尝试中,您使用User覆盖了导出对象,因此checkName丢失了。相反,做

function User(name){
   this.name = name;
}

User.prototype.getName = function () {
   return this.name;
};

User.checkName = function (name) { /*
^^^^ */
   return name === 'johnSnow';
};

module.exports = User;

Or alternatively you might want to write

或者你可能想写

module.exports = User;
module.exports.checkName = function (name) {
   return name === 'johnSnow';
};

更多相关文章

  1. javaES6箭头函数的全新特性
  2. JavaScript学习-5——异步同步、回调函数
  3. 什么“返回此”在javascript函数中做什么?
  4. jQuery和AJAX - 使用Ajax添加的对象动态不适用于jQuery函数?
  5. Javascript偏函数与柯里化
  6. 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事
  7. Python 内置函数及excel操作
  8. Python3 函数式编程(高阶函数)
  9. python中range()函数的用法--转载

随机推荐

  1. Android中 Rect类
  2. Android:SeekBar和RatingBar控件
  3. Android 安装环境搭建
  4. Android笔记--短信与拨号
  5. android常用UI控件的使用例子
  6. Android能用Linux打败Linux手机吗?
  7. Android中实现滑动的七种方式总结
  8. 大虾们的 android 浅谈
  9. android 解决输入法键盘遮盖布局问题
  10. android学习笔记(2)---第一个Android应用程