Nodejs module extends with other module - javascript

Hi i have parent module like this.
// usermgmt.js
var usermgmt = function () {};
usermgmt.prototype.test = function () {
return "test";
};
usermgmt.private = function () {
return "private";
};
module.exports = new usermgmt();
and a Child prototype class like this.
// authentication.js
var usermgmt = require('./usermgmt');
var authentication = function () {};
authentication.prototype.callParent = function () {
usermgmt.private();
};
module.exports = new authentication();
How i implement inheritance? I searched by google but no solution works for me.

Here's a typical way to export a base class and then import it and inherit from it using the more modern syntax:
// a.js
class A {
constructor() {
}
testA() {
return "testA";
}
}
module.exports = A;
Then, in a separate file:
// b.js
const A = require('./a.js');
class B extends A {
constructor() {
super();
}
testB() {
return "testB";
}
}
let x = new B();
x.testA(); // "testA" - this is inherited obviously
x.testB(); // "testB"

As #jfriend00 said, I write these functions with class keyword which is a syntactic sugar for your code!
usermgmt.js
// usermgmt.js
class usermgmt {
constructor() {
}
test() {
return "test";
}
private() {
return "private";
}
}
module.exports = usermgmt;
Write authentication like this.
authentication.js
// authentication.js
var Usermgmt = require('./usermgmt.js');
class authentication extends Usermgmt {
constructor() {
super();
}
callParent() {
console.log(this.private());
}
authFunction() {
console.log(':: authFunction ::');
this.callParent();
}
}
module.exports = authentication;
And usage for authentication will be:
var Authentication = require('./authentication.js');
let auth = new Authentication();
auth.callParent();
auth.authFunction();
console.log(auth.test());
1) Use class and extends syntax which is easier.
2) Return Class and not its instance

Related

How to wrapper multiple classes in different files into a single function in typescript

I am facing an issue with typescript build while trying to wrapper multiple classes into a single function.
Below is the sample code.
// AppState.ts
export class AppState {
static id: string;
}
// AppLogic.ts
import { AppState } from './AppState'
export class AppLogic{
constructor(id : string){
AppState.id = id;
}
public getAppID() : string{
return AppState.id;
}
}
// main.ts
import { AppLogic } from './AppLogic';
export function AppwrapAPI(id : string): any{
class AppAPI{
private app : AppLogic;
constructor(id : string){
this.app = new AppLogic(id);
}
public getAppID() : string{
return this.app.getAppID();
}
}
return new AppAPI(id);
}
<!DOCTYPE html>
<html>
<head>
<title>Test app</title>
</head>
<body>
<script type="module">
import { AppwrapAPI } from "./dist/main.es.js";
let a1 = new AppwrapAPI("123");
alert(a1.getAppID()); ///"123"
let a2 = new AppwrapAPI("321"); ///"321"
alert(a2.getAppID());
alert(a1.getAppID()); ///"321" <<--- wrong data
</script>
</body>
</html>
The above ts project generates the following js code using rollup built.
var AppState = /** #class */ (function () {
function AppState() {
}
return AppState;
}());var AppLogic = /** #class */ (function () {
function AppLogic(id) {
AppState.id = id;
}
AppLogic.prototype.getAppID = function () {
return AppState.id;
};
return AppLogic;
}());function AppwrapAPI(id) {
var AppAPI = /** #class */ (function () {
function AppAPI(id) {
this.app = new AppLogic(id);
}
AppAPI.prototype.getAppID = function () {
return this.app.getAppID();
};
return AppAPI;
}());
return new AppAPI(id);
}export{AppwrapAPI};//# sourceMappingURL=main.es.js.map
In this code, the AppwrapAPI function wraps only the AppAPI function instead of all the functions and the AppState function is outside the AppwrapAPI function which creates an issue when I create multiple instances for the AppwrapAPI function.
let a1 = new AppwrapAPI("123");
alert(a1.getAppID()); ///"123"
let a2 = new AppwrapAPI("321"); ///"321"
alert(a2.getAppID());
alert(a1.getAppID()); ///"321" <<--- wrong data
I want to wrapper all the three classes AppState, AppLogic, AppAPI inside the AppwrapAPI function so that the AppState is not shared between the multiple instances.
Similar to the below code
"use strict";
function AppwrapAPI(id) {
class AppState {
}
class AppLogic {
constructor(id) {
AppState.id = id;
}
getAppID() {
return AppState.id;
}
}
class AppAPI {
constructor(id) {
this.app = new AppLogic(id);
}
getAppID() {
return this.app.getAppID();
}
}
return new AppAPI(id);
}
let a1 = AppwrapAPI("123");
console.log(a1.getAppID()); /// output : 123
let a2 = AppwrapAPI("321");
console.log(a2.getAppID()); /// output : 321
console.log(a1.getAppID()); /// output : 123
Right now I manually modifying the generated code to avoid this issue but it gives me some other issue while debugging with the source map generated from the old file.
Can anyone suggest to me how to modify the typescript code to get the single function that wraps all the classes in the typescript project?

Is a Node.js module a singleton?

I used to implement singleton this way:
class MySomething {
constructor(props) {}
}
let myInstance = null;
module.exports = (props) => {
//first time call
if(props) {
myInstance = new MySomething (props);
return myInstance;
} else {
return myInstance;
}
this assumes that at app.js (entry file) I will call first:
require('./MySomething')(props)
then everywhere in the project I use:
const instanceOfSomething = require('./MySomething')();
I discovered that every time I got a new instance!
What's wrong in my code?
I tried also this way:
class MySomething {...}
const mySomething = (function() {
let myInstance = null;
return {
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
})();
module.exports = mySomething;
and I got the some problem when importing this module from different files, anyone can explain to me?
every require of file create new instance of mySomething
UPDATE
I tried this example now:
class MySomething {...}
const mySomething = {
myInstance: null,
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
};
module.exports = mySomething;
The same problem happened, maybe it is related to my project structure, I will explain it here:
the code below belongs to module "facts"
facts folder contains a folder named "dao" this folder contains MySomething.js (the singleton)
in the facts/index.js I have:
const Localstorage = require('./dao/MySomething');
exports.init = (path) => {
Localstorage.init(path)
}
exports.Localstorage = Localstorage;
Now in a folder named "core" which contains the "facts" folder I re-exported the Localstorage again in "index.js" like this:
const facstModule = require('./facts');
exports.Localstorage = facstModule.Localstorage;
Then in "schedule" folder which contains "Runtime.js" within I write:
const { Localstorage } = require('../core');
setTimeout(() => {
const localstorageIns = Localstorage.getInstance(); //this is always null!
}, 5000)
In app.js file (entry point) I did:
const facts = require('./src/facts');
facts.init(__dirname);
Normally instance will be created before the timeout execute the callaback,
But I noticed that there two instance of Localstorage which is singleton
the cleanest way to do a singleton is
class MyClass () { ... }
module.exports = new MyClass()
if you need a singleton that gets instantiated once, I would do:
class MyClass () { ... }
let myClass
const MyClassSingleton = (...args) => {
if (myClass) {
return myClass
}
myClass = new MyClass(...args)
return myClass
}
module.exports = MyClassSingleton
Every require of file create new instance of mySomething because every time you return new object with init method and getInstance method.
If you need singleton you need do like this:
class MySomething {
constructor() {
if (!MySomething.instance) {
MySomething.instance = this;
}
}
getInstance: function() {
return MySomething.instance;
}
}
module.exports = MySomething;
class Singleton {
constructor() {
this.my_obj;
}
static makeObject() {
if (!this.my_obj) {
this.my_obj = new Singleton();
}
return this.my_obj;
}
add() {
return 1
}
}
// so to get the object we need to call the makeobject method
const obj = Singleton.makeObject()
console.log(obj.add());

Can we get the attributes of a javascript class?

I have this javascript class :
class UserDTO {
constructor(props) {
this.username = props.username;
this.birthday = props.birthday;
}
}
and I have a class Utils that convert an Entity to DTO:
class Utils {
convertEntityToDTO (entityObj, DTOClass) {
// entityObj is an instance of a Entity,
// DTOClass is a class not an instance
let objDTO = new DTOClass();
Object.getOwnPropertyNames(entityObj)
.filter(prop => DTOClass.hasOwnProperty(prop))
.forEach(prop => {
objDTO[prop] = entityObj[prop];
});
}
}
this doesn't work a class ; hasOwnProperty just work with object; is a way to verify if a property is an attribute of a class or not ? or I have to create an instance to test ?
You can use hasOwnProperty on the instance and getOwnPropertyNames :
class A {
constructor() {
this.ex = 'TEST';
}
}
var a = new A();
console.log(a.hasOwnProperty('ex'));
console.log(Object.getOwnPropertyNames(a));
If instead you want the methods, you need to get the prototype:
class B {
constructor() {}
exMethod() {
console.log('test');
}
}
var b = new B();
console.log(Object.getPrototypeOf(b).hasOwnProperty('exMethod'));
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(b)));

Object composition pattern example

I am learning JS and have came across an interesting article about object composition pattern in JS. What I am wondering in this code:
let Magic = (superclass) => class extends superclass {
shout() {
if (super.shout) super.shout();
console.log('Power and wisdom.');
}
};
let Fighting = (superclass) => class extends superclass {
shout() {
if (super.shout) super.shout();
console.log('Strength an courage.');
}
};
class Creature {
constructor(name) {
this.name = name;
}
shout() {
console.log(`I'm ${this.name}! Oorah!!`);
}
};
class DwarfWizard extends Fighting(Magic(Creature)) {
courseObjects(object = {}) {
object.curse = true;
return object;
}
}
new DwarfWizard('Thordalf').shout();
// "I'm Thordalf! Oorah!! Power and wisdom. Strength an courage."
What is the purpose of the function courseObjects in the DwarfWizard class?
courseObjects(object = {}) {
object.curse = true;
return object;
}
I still get the same result even when I comment out the function, so I am wondering what is it's purpose?

es6 class pass this to a static class functions

i have this class
import { ObjectUtilities } from '~/utils/';
class Object{
constructor(object) {
Object.assign(this, { ...object });
}
utils = ObjectUtilities;
}
and this class with the statis method also (class contains many static methods)
class ObjectUtilities {
static getKey(object){
return object.key;
}
}
and i want to know if its possible to share the "this" from the Object class
to the static method "getKey(object)"
want to do it as:
let x = new Object(object);
x.utils.getkey(this);
(ObjectUtilities as many static funcs i dont want to do it for each of them)
thanks for helping me out...
You can add a constructor to the ObjectUtilities class where you bind the given context to the getKey function:
class ObjectUtilities {
constructor(_this) {
this.getKey = this.getKey.bind(_this);
}
getKey() {
return this.key;
}
}
class MyObject {
constructor(object) {
Object.assign(this, { ...object });
this.utils = new ObjectUtilities(this);
}
}
const objectFoo = { key: 'foo' };
const objectBar = { key: 'bar' };
let x = new MyObject(objectFoo);
let y = new MyObject(objectBar);
console.log(x.utils.getKey(), y.utils.getKey());

Categories

Resources