是否可以从节点js中的同一模块导出构造函数和一些正常函数?
16lz
2021-01-22
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';
};
更多相关文章
- javaES6箭头函数的全新特性
- JavaScript学习-5——异步同步、回调函数
- 什么“返回此”在javascript函数中做什么?
- jQuery和AJAX - 使用Ajax添加的对象动态不适用于jQuery函数?
- Javascript偏函数与柯里化
- 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事
- Python 内置函数及excel操作
- Python3 函数式编程(高阶函数)
- python中range()函数的用法--转载