包括Node.js中另一个文件的JavaScript类定义 [英] Including JavaScript class definition from another file in Node.js
本文介绍了包括Node.js中另一个文件的JavaScript类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为Node.js编写一个简单的服务器,我正在使用我自己的类 User
,它看起来像:
I'm writing a simple server for Node.js and I'm using my own class called User
which looks like:
function User(socket) {
this.socket = socket;
this.nickname = null;
/* ... just the typical source code like functions, variables and bugs ... */
this.write = function(object) {
this.socket.write(JSON.stringify(object));
}
};
然后在这个过程中我实例化了很多:
and then later in the process I'm instantiating it a lot:
var server = net.createServer(function (socket) {
/* other bugs */
var user = new User(socket);
/* more bugs and bad practise */
});
我可以将用户
类定义移动到另一个javascript文件并以某种方式包含它?
Can I move my User
class definition to another javascript file and "include" it somehow?
推荐答案
甚至你可以简单地这样做
And even you can simply do this
user.js
class User {
//...
};
module.exports = User;
server.js
const User = require('./user.js');
// Instantiate User:
let user = new User();
P.S。并且不要使用全局变量。它会在未来产生潜在的冲突。
P.S. And don't use globals. It creates potential conflicts in the future.
这篇关于包括Node.js中另一个文件的JavaScript类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文