开发者

Node.js modules vs Objects

开发者 https://www.devze.com 2023-02-11 15:48 出处:网络
I have been playing around with node.js, and coming from a Java background, I am struggling to differentiate between modules and the typical concept of objects in JavaScript.

I have been playing around with node.js, and coming from a Java background, I am struggling to differentiate between modules and the typical concept of objects in JavaScript.

When implementing a modules, I am currently do开发者_Go百科ing it this way:

// someModule.js
var privateVariable;
this.sampleFunction = function() {
   // ...
}

Now, the way I am using this module in another place is:

var moduleName = require('./someModule');

var foo = moduleName.sampleFunction();

I don't know if this is the right way to do modular development in node.js - because I realized I am not actually using objects, like using new() - which I would need to do when I want to have collections etc. What is the right way to proceed here if I want a collection of person objects - how will my module and it's definition look like?


// someModule.js
var privateVariable;
this.Person = function(firstName, lastName) {
   this.firstName = '...';
}

And then:

var moduleName = require('./someModule');

var foo = new moduleName.Person('foo', 'bar');


A module is a namespace to hold a bunch of related items in. So you might have a "person-collections" module, which contains several types of person collections, such as "lineup", "pile" and "dumpster".

Depending on whether you're using an oo or a functional style of writing, the actual code will look different.

0

精彩评论

暂无评论...
验证码 换一张
取 消