JavaScript - Instantiate from require - javascript

I have a Node program. This program is importing some code. That code looks like the following:
sample.js
function SampleModel() {
this.name = 'Test';
}
module.exports = SampleModel;
I am using SampleModel in another file. Currently, I am successfully using it like this:
another.js
var SampleModel = require('./sampleModel');
var model = new SampleModel();
For the purpose of education, is there a way to condense these two lines down to a single line of JavaScript? If so, how?
Thank you!

Like this:
var model = new (require('./sampleModel'))();
It's quite common to access the required module directly in the import line, but you'll mostly see property access (like require('events').EventEmitter).

Related

How can I extend a class in Node JS by my custom constructor?

I have the following in a Node Js model. This file exists in another project that cannot be changed but is locally available to the other projects.
module.exports = {
base: require('*/cartridge/models/product/decorators/base'),
availability: require('*/cartridge/models/product/decorators/availability')
};
All the methods here act like constructors of the class Product. Now I want to add another attribute that should be available when I try to access Product.badge. For this, I have tried to extend the above model in the following way:
var indexBase = require('*/cartridge/models/product/decorators/index');
indexBase.badge = require('*/cartridge/models/product/decorators/badge');
module.exports = indexBase;
But it seems throw an error, I have tried to log the Badge Type, but I still cannot access the badge type here.
I am calling the above object as the following:
var decorators = require('*/cartridge/models/product/decorators/index');
decorators.badge(product, variantProduct);
I want to know how can I extend an existing class as I want to add a custom constructor?
Here only the syntax is based on Node Js but this code is written for SFRA in Salesforce B2C Commerce.
All you need to do is in the index.js file:
var indexBase = module.superModule;
instead of:
var indexBase = require('*/cartridge/models/product/decorators/index');
and it will work perfectly fine.

Node.js issues with exporting functions

I have a few questions about the nature of exporting functions in NodeJS:
Firstly this is an acceptable way to export a function:
exports.bread = function bread() {
return 'bread: 2';
};
However, it is not possible (maybe?) to export a function using this method:
function pullData(pair) {
console.log(pair);
}
module.exports = pullData;
The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?
Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...
So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?
Screenshots from project:
When you write module.exports = something you are exporting only one thing. So your code should look like this
var pullData = require('./getTicker')
pullData('TEST')
If you want to write it the way you have done so then you need to export it differently, as only part of the module.exports object.
You can do this by writing
exports.pullData = pullData in your getTicker file.
Then you can import it and use it like you did:
var trackData = require('./getTicker')
trackData.pullData('TEST')
Try putting pullData in curly brackets:
module.exports = {pullData}
and when you require it, do this:
const {pullData} = require("./getTicker");
Hope it'll work.

Getting element from pageobject in protractor

Im writing some Protractor testcases by using a pageobject. However im having trouble using elements directly from the Pageobject file, in the spec file.
Possibly im missing some JS nuance, since i havent written that much in JS.
i would like to use some elements defined in Pageobject like so:
var PageObject = function()
{
var loginUsername = element(by.id('loginusername'));
//other methods
};
module.exports = PageObject;
to be used in my spec file like so:
var PageObject = require('./pageObject.page.js');
describe( ' Login page ', function(){
it('type something in the usernamefield', function(){
var pageObject = new PageObject();
pageObject.get();
pageObject.loginUsername.sendKeys('Test');
});
});
Using methods (for example get but also others)works fine, but using elements directly causes some undefined errors.
Im trying to copy from something like this, where supposedly it should work.
https://ramonvictor.github.io/protractor/slides/#/33
Something you are missing,
bind your variable to object in pageObject.page.js, using this keyword
var PageObject = function()
{
this.loginUsername = element(by.id('loginusername'));
......
};
module.exports = PageObject;
In Spec first get the real application and do real work
it('type something in the usernamefield', function(){
browser.get('"https://....');
var pageObject = new PageObject();
pageObject.loginUsername.sendKeys('Test');
});
This works for me perfect,

How to use a JavaScript method/object that has been defined in another file?

I have a some JavaScript with a complex structure. Because I'm new comer to JavaScript (only understanding some basic concepts) I don't know how to use it properly.
I have two files : Circle.js and Line.js. In Circle.js, I want to use a class object defined in Line.js:
In file Circle.js :
Helper.using('py.Figures', function (ns) {
ns.Circle = function (params) {
// some additional methods and code here
}
}
And in Line.js is :
Helper.using('py.Figures', function (ns) {
ns.Line2Point = function (params) {
// some addition methods and code here
};
}
In Figures.Circle, in ns.Circle I want to use Line2Point but I don't know how.
I think it should be :
line = new ns.Line2Point(params);
But It seem doesn't work.
According to Helper Class, ns will point to helper.using, in this case py.Figures. Does it mean, ns is the same object/reference in both the files?
I don't think this is doable in Javascript directly across files. If they are part of the same namespace you could share some 'global' objects to achieve this have the line2points and circles attach themselves to that global object:
Ex:
var myShapesNameSpace = {};
Circle.js:
(function(){
var circle = {};
circle.method1 = function(){...}
circle.method2 = function(){...}
myShapesNameSpace.Circles = circle;
})(window.myShapesNameSpace = window.myShapesNameSpace || {}); //check if namespace object exists. Else create a new blank one.
Line.js:
(function(){
var line= {};
line.method1 = function(){...}
line.method2 = function(){...}
myShapesNameSpace.Lines= line;
})(window.myShapesNameSpace = window.myShapesNameSpace || {});
Now you can check for the existence of myShapesNameSpace.Circles or .Lines and call the corresponding methods accordingly.
You can include files in javascript and reference objects across files unless they are exported in some global form either via window or your define global
Welcome to Javascript, the shit parts. Require.js was designed precisely for this because the creators of JS, well, I guess thought that everyone would write every program in one file.
RequireJS
It was designed for web use but can be used elsewhere too (locally, with Node, etc.)

Inheriting through Module.exports in node

This is probably me being stupid...
I'm using node with express and I have a seperate file using exports for routes. Above it, I require and cast to a variable, a package I have installed using npm.
var passwordHash = require('password-hash');
app.get("/signup", routes.signup);
inside routes.signup, I have:
passwordHash.generate(req.form.username, {algorithm: 'sha512'})
and it throwing an error saying passwordHash is undefined. How can I go about "inheriting" said require call?
You can also do the following (say this code is defined in app.js):
module.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
in routes.signup:
var passwordHash = module.parent.passwordHash; // from app.js
passwordHash.generate(req.form.username, {algorithm: 'sha512'});
Separate files have separate scopes, so if you want to use passwordHash inside of your other file, then you need to call require('password-hash'); in that file too.
You can move your variables via app variable which should be accessible everywhere. Try to do something like that:
app.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
The other thing that you might try is to use global variable, which means removing var from passwordHash. Not sure if this will work out for express, but it's worth checking.
passwordHash = require('password-hash');
app.get("/signup", routes.signup);
Let me know if it helped.
I know this question is old, but this would've helped me: Use exports!
So if I have a file called Index.js with this:
var model = require("./Model");
function test()
{
model.setMyVar("blah");
console.log(model.myVar);
}
My Model.js would look like this:
var myVar;
exports.myVar = myVar;
function setMyVar(value)
{
this.myVar = value;
}
exports.setMyVar = setMyVar;

Categories

Resources