node.js instantiate class multiple times - javascript

I have a class file that creates socket connections based on the parameter passed in during instantiate.
When I try to instantiate this file multiple times (for loop) it looks like the node.js is handling it like singleton.
Is there a way I can create new instances from a same js file that can hold its own arguments passed?
app.js
for(var i....){
require('./controller/sockets')(param[i]);
}
./controller/sockets
var util = require('util');
var param
Socket = function(iParam) {
param = iParam;
};
util.inherits(Socket,EventEmitter);
Socket.prototype.test = function(){
return param;
};
module.exports = Socket;
Thank you!

Your constructor doesn't actually create anything. All it does it store an argument in a variable. So, when you call it N times, that's all it does is store a different value into the same variable N times in a row.
Your code is essentially doing this:
var param;
var Socket = function(iParam) {
param = iParam;
}
for(var i....){
Socket(param[i]);
}
It is not clear to me what you want it to do, but perhaps the constructor needs to create an object (probably using new), initialize it and then return it.
If you want a new Socket object back from each call to the constructor, then you can do it like this:
var util = require('util');
function Socket(iParam) {
this.param = iParam;
}
util.inherits(Socket,EventEmitter);
Socket.prototype.test = function(){
return this.param;
};
module.exports = function(x) {
return new Socket(x);
};

Related

I am getting: Cannot call method 'someMethodName' of undefined when trying to access an object in a javascript clas

I am almost new to JavaScript, and I am trying to access an object within a class. This is my class definition in a file called analysis.po.js:
var AnalysisPage = function () {
(some code here)
this.getSpousesCreditBureau = function() {
return {
pdScore: getSpousesCreditBureauElement('pdScore'),
qualification: getSpousesCreditBureauElement('qualification'),
estimatedFee: getSpousesCreditBureauElement('estimatedFee'),
currentDebt: getSpousesCreditBureauElement('currentDebt'),
maxDebt: getSpousesCreditBureauElement('maxDebt'),
arrears: getSpousesCreditBureauElement('arrears'),
segment: getSpousesCreditBureauElement('segment'),
bpGlobalRisk: getSpousesCreditBureauElement('bpGlobalRisk'),
groupGlobalRisk: getSpousesCreditBureauElement('groupGlobalRisk')
};
};
(some other code here)
};
module.exports = new AnalysisPage();
This is the piece of code where I try to get the object getSpousesCreditBerauElement in another file called analysis.spec.js:
var App = require('../app.po.js'),
Util = require('../util.js'),
AnalysisPage = require('./analysis.po.js'),
AnalysisData = require('./analysis.data.js');
(some code here)
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());
(some other code here)
The error I am getting is:
Cannot call method 'getSpousesCreditBureau' of undefined
You're not actually exporting AnalysisPage and you're not calling it correctly.
Export the class with:
module.exports = AnalysisPage;
In comparison
module.exports = new AnalysisPage();
Exports an instance of the class.
The right way to call it is then:
var instance = new AnalysisPage();
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());
(Original question has been modified, code was:)
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(AnalysisPage.getSpousesCreditBureau());
You can export just the instance, in that case call it like:
var instance = require('./analysis.po.js');
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());
So no new anywhere.
Did you tried:
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());
When you access the method like this AnalysisPage.getSpousesCreditBureau() you are not accessing the instance, but the class definition.

How can a module in node.js maintain state?

I have two different js files that use the same module.
file1.js:
var mod1 = require('commonmodule.js');
mod1.init('one');
file2.js:
var mod2 = require('commonmodule.js');
mod2.init('two');
(both these files file1.js, file2.js are loaded inside my server.js file, they themselves are modules)
now in commonmodule.js:
var savedName;
exports.init = function(name)
{
savedName = name;
}
exports.getName = function()
{
return savedName;
}
I noticed that this savedName is always overridden dependent on who set it last.So it doesn't seem to work. How would I get a module to maintain state?
Note: I also tried to set savedName as exports.savedName in the commonmodule.js but it doesn't work either
You can just create a new instance every time the module is required:
commonmodule.js
function CommonModule() {
var savedName;
return {
init: function(name) {
savedName = name;
},
getName: function() {
return savedName;
}
};
}
module.exports = CommonModule;
file1.js
var mod1 = new require('./commonmodule')();
mod1.init('one');
console.log(mod1.getName()); // one
file2.js
var mod2 = new require('./commonmodule')()
mod2.init('two');
console.log(mod2.getName()); // two
modules in and of themselves are simple object instances. A single instance will be shared by all other modules (with the caveat that it is loaded via the same path). If you want state, use a class and export a constructor function.
example:
//Person.js
function Person(name) {
this.name = name;
}
module.exports = Person;
To use it:
var Person = require("./Person");
var bob = new Person("Bob");
Modules are not like classes/class functions; by default, mod1 and mod2 will refer to the same module due to caching. To keep track of per-instance state, you'll need a constructor function or something similar inside your module, e.g.
var mod = require('commonmodule.js');
var state = new mod.init('one');
Where init defines the stateful object. You could also have it return an object literal, in which case you wouldn't have to use new (e.g. var state = require('commonmodule.js').init('one');)
(This is assuming you want the module to have other, shared state in addition to the per-instance state; if that is not the case, Peter Lyons' method would be simpler.)
You could perhaps remove from cache your module. Like that:
file1.js:
var mod1 = require('commonmodule.js');
mod1.init('one');
file2.js:
delete require.cache[require.resolve(modulename)];
var mod2 = require('commonmodule.js');
mod2.init('two');
But I don't find it very convenient and clean.
But you could also clone it or make a small proxy.
Also you could create classes:
var savedName;
exports.obj = {}
exports.obj.prototype.init = function(name)
{
savedName = name;
}
exports.obj.prototype.getName = function()
{
return savedName;
}
Then :
var mod2 = new (require('commonmodule.js'))();
mod2.init('two');

What is the best way to define dependent variables in an object?

In the Google developers recommendation for optimizing JavaScript code, they mention that the best way to declare/initialize new variables for object is to use the prototype. For instance, instead of:
foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};
Use:
foo.Bar = function() {
this.prop3_ = [];
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';
However, in my case I have a dependency between variables, for instance:
var appv2 = function(){
this.start(this.person, this.car);
};
appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(this.toWhom);
appv2.prototype.car = new car();
appv2.prototype.start = function(person, car){
console.log('start for appv2 is called');
person.sayHello('me app v2');
car.brand();
};
new appv2();
Using this.toWhom outside of the main constructor body or a method function of the object will yield undefined. To solve this I could use appv2.prototype.toWhom instead of this.toWhom or I could declare my dependent variables inside of the main constructor body.
But I would like to know what is the best way, in terms of performance, to accomplish this?
Thanks
To reference toWhom while creating person, you can either store the value in a separate variable:
var toWhom = appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(toWhom);
Or, reference it from the prototype, as you suspected:
appv2.prototype.person = new person(appv2.prototype.toWhom);
The reason this.toWhom is undefined is because this doesn't refer to an instance of appv2 there.

Result of expression 'xxxx' is not a constructor in JS

Trying to create an object in Javascript (for Appcelerator/Titanium).
The "object" is defined like this:
function server () {
this.cacheimages = 0;
this.login = "";
this.name = "";
this.root = "";
this.signup = "";
this.useimages = 0;
this.userexists = "";
this.isdefault = 0;
return this;
}
In the same file, in another function when I run this line: var server = new server(); I get the error Result of expression 'server' is not a constructor.
I have tried it with and without the "return" line, neither work. What am I doing wrong?
What happens if you change the name of the variable?
var server2 = new server();
Functions are 'first class citizens' in javascript, meaning they are variables (or better still: objects, like everything in javascript is an object). So your constructor function could also be written as
var server = function() {
//[...]
}
Now, if you declare a new variable called server, this overwrites the constructor function, being a variable too.
It's common practice to upcase the name of constructor functions. If you use function Server() { ... }, var server = new Server (no need for parenthesis by the way) you're fine.

Calling javascript method from from inside object

I am struggling with methods in JavaScript.
obj = function(){
this.getMail = function getMail (){
}
//Here I would like to run the get mail once but this.getMail() or getMail() wont work
}
var mail = new obj();
mail.getMail();
How do I make the method in a way that I can run it both inside the object and from the outside
Thanks
When you define the function use the name just once, like this:
obj = function(){
this.getMail = function(){
alert("bob");
}
}
Now you can use this.getMail() in there, you can see a working example here.
here you go:
var obj = function() {
function getMail() {
alert('hai!');
}
this.getMail = getMail;
//Here I would like to run the get mail once but this.getMail() or getMail() wont work
getMail();
}
var mail = new obj();
mail.getMail();
Building a robust definition for your object is recommended. Build a prototype for it, then if you ever need two or more, you can make instances of them. I show below how to build a prototype, add methods that call eachother, and how to instantiate the object.
obj = function () {} //define the empty object
obj.prototype.getMail = function () {
//this is a function on new instances of that object
//whatever code you like
return mail;
}
obj.prototype.otherMethod = function () {
//this is another function that can access obj.getMail via 'this'
this.getMail();
}
var test = new obj; //make a new instance
test.getMail(); //call the first method
test.otherMethod(); //call the second method (that has access to the first)

Categories

Resources