Check inheritance in nodejs - node.js

What is the best way to check inheritance in nodejs?
I'm trying to use instanceof in a instance of a class of another module that inherits a class for this module.
file a.js
class A{
}
class B extends A{
}
var b = new B();
b instanceof A ///this work
global.c instanceof A //this doesn't work
module.exports = A;
file c.js
var A = require("./a");
class C extends A{
}
global.c = new C();

It is because of loading issue! When you load class C, it request class A and it is run before the C is defined.
I have tried it myself, if I did it as you mentioned and requested both classes, the second one comparision failed.
However this one works:
a.js
class A{
callMeLaterAligator(){
console.log(b instanceof A) ///this work
console.log(global.c instanceof A) //this now work
}
}
class B extends A{
}
var b = new B();
module.exports = A;
c.js
var A = require("./a");
class C extends A{
}
global.c = new C();
The main method
require('services/c');
const a = require('services/a');
const aInst = new a();
aInst.callMeLaterAligator();
having output
true
true
To better understand whats going on, I have created this example
a.js
console.log('Hello, I am class A and I am not yet defined');
class A{
}
class B extends A{
}
var b = new B();
console.log('Hello, I am class A and I will compare something');
console.log(b instanceof A) ///this work
console.log(global.c instanceof A) //this doesn't work
module.exports = A;
c.js
console.log('Hello, I am class C and I am not yet defined');
var A = require("./a");
console.log('Hello, I am class C and I will now try to defined myself');
class C extends A{
}
console.log('Hello, I am class C and I am defined');
global.c = new C();
console.log('Hello, I am class C and I am in global.c');
server.js
require('services/c');
Having this output
Hello, I am class C and I am not yet defined
Hello, I am class A and I am not yet defined
Hello, I am class A and I will compare something
true
false
Hello, I am class C and I will now try to defined myself
Hello, I am class C and I am defined
Hello, I am class C and I am in global.c
If you change it to require "a" first, then the C is not loaded at all
server.js change :
require('services/a');
Having this output
Hello, I am class A and I am not yet defined
Hello, I am class A and I will compare something
true
false

Related

how to typecast T extends Class in typescript

I want to avoid using any for clazz. Casting it to A doesn't allow me to create a new instance as it assumes it's an abstract class. What would be the correct type to cast clazz to?
abstract class A {}
class B extends A {}
class C extends A {}
class D extends A {}
const clazz: any = getOneOfBCDRandom();
const c = new clazz();
getOneOfBCDRandom<T extends A>(): T {
return [B, C, D][Math.floor(Math.random() * 3)]
}
i removed the private state from the getOneOfBCDRandom function as it was a mistake.
The solution was to not use generics but:
new () => A
so this works as expected:
abstract class A {}
class B extends A {}
class C extends A {}
class D extends A {}
const clazz: new () => A = getOneOfBCDRandom();
const c = new clazz();
getOneOfBCDRandom(): new () => A {
return [B, C, D][Math.floor(Math.random() * 3)]
}
Using generics was just my first approach

How to mock with JestJS injected dependency in class ES6?

I'm trying to get some dependance inversion going in a small NodeJS project. I want to have mocked instances of personal classes that I can inject in other classes.
This is for the lates node and jest version, I have read Jest documentation and nothing seem to be what I'm looking for.
class A {
getStr(): string {
return "bob";
}
}
class B {
private a: A;
constructor(a: A){
this.a = a;
}
getA(): string {
return a.getStr();
}
}
const b = new B(mocked instance of A)
I expect to be able to interact with the injected mock and see if it's been called in unit testing.
Assuming you would like to spy on the functions of A, you could do it as follows (if you would like to keep using classes notation):
class MockA {
constructor() {
this.getStr = jest.fn()
}
}
const mockedA = new MockA()
const b = new B(mockedA)
Then to test that it was called, you could do it as follows:
b.getA();
expect(a.getStr.mock.calls.length).toBe(1)
To create the mock without the class, you could do so as follows:
const mockedGetStr = jest.fn()
const b = new B({ getStr: mockedGetStr })
b.getA();
expect(a.getStr.mock.calls.length).toBe(1)

NodeJS ES6: Class module exports

Thank for read my topic, today, i have a quest about classes in es6, i don't why vi go error when i run.
I have class A:
var B = require("./b");
class A{
constructor() {
console.log("Constructor class A");
}
helloLoop() {
console.log("A: Hello loop");
B.hello();
}
helloWithoutLoop() {
console.log("A: Hello without loop");
}
}
module.exports = new A();
and class B:
var A = require("./a");
class B{
constructor() {
console.log("Constructor class B");
}
hello() {
console.log("B: Hello");
A.helloWithoutLoop();
}
}
module.exports = new B();
and a test:
var A = require("./a");
var B = require("./b");
A.helloLoop();
When i run test, i receive a error:
A.helloWithoutLoop();
TypeError: A.helloWithoutLoop is not a function
at B.hello ({work-sapce}\test\b.js:9:11)
I don't that happen!
Please help me!
Thanks very much!
You have a circular dependency. Your main file requires A which requires B which requires A (circular). Can't do that. The second attempt to require A before A itself has finished loading will return null which is why you get the weird error you do.
The usual solution is to find the common code and put it in a third module that both the others can load and not have A loading B and B loading A.
Have A loading C and B loading C.
Or, even simpler, just put A and B in the same file so there is no circular loading between them.
This is how you can call them :
import A from './A';
import B from './B';
A.helloLoop();
This is class A :
import B from './B';
class A{
constructor() {
console.log("Constructor class A");
}
helloLoop() {
console.log("A: Hello loop");
B.hello();
}
helloWithoutLoop() {
console.log("A: Hello without loop");
}
}
export default new A();
This is class B :
import A from './A';
class B{
constructor() {
console.log("Constructor class B");
}
hello() {
console.log("B: Hello");
A.helloWithoutLoop();
}
}
export default new B();
see the difference ?

How to pass context Implicitly for constructors in Kotlin

I am trying to make the construction of instances of a class depending on the scope in which they are defined without using explicit parameters.
This is part of a port from Python to Kotlin but the main idea would be something like:
var d = MyClass()
use_scope(contextAForScope) {
var a = MyClass()
use_scope(contextBForScope) {
var b=MyClass()
}
}
In this example the d constructor would use a default context, a constructor would use contextAForScope and b constructor would use contextBForScope (use_scope is just a placeholder here).
Something like implicit contexts?
Of course, I could make the constructor parameter explicit but this will potentially be used many times in a single scope and I would prefer not to define an additional variable.
class MyClass(val context: Int)
fun MyClass() = MyClass(0)
interface MyClassScope {
fun MyClass(): MyClass
}
object ContextAForScope : MyClassScope {
override fun MyClass() = MyClass(1)
}
object ContextBForScope : MyClassScope {
override fun MyClass() = MyClass(2)
}
inline fun useScope(scope: MyClassScope, block: MyClassScope.() -> Unit) {
scope.block()
}
fun main(args: Array<String>) {
val d = MyClass()
useScope(ContextAForScope) {
val a = MyClass()
useScope(ContextBForScope) {
val b = MyClass()
}
}
}
Use a factory function to create your class. If you name the function like the class, it looks like a constructor.
Define an interface with the same factory function and two objects for the scopes.
Define a function that takes the scope and the initializer block.
Now you can use the useScope-Function and within the block the right factory function is invoked.
with is what you are looking for:
class MyClass()
var d = MyClass()
fun main(args: Array<String>){
var c = "c: Could be any class"
var d = "d: Could be any class"
with(c) {
// c is "this"
var a = MyClass()
print(c) // prints "c: Could be any class"
with(d) {
// d is "this"
var b = MyClass()
}
// b is undefined in this scope
}
// a is undefined in this scope
}
with takes a lambda as argument an everything in that lambda is only defined in that scope.

What would the UML sequence diagram of the following code look like?

What is UML sequence diagram of the following code featuring a class with two inner classes where each one is instantiated once as seen in the main function?
class A{
class B{
C f(){}
}
class C{}
static void main(){
A a = new A()
B b = new B();
C c = new C();
c = b.f();
}
}
You could use an automated sequence diagram generator in Eclipse such as Diver: Dynamic Interactive Dynamic Interactive Views For Reverse Engineering. It generates both static and dynamic sequence diagrams and looks to answer your question.
I adjusted your code a bit to make it compile and used Diver to generate a sequence diagram:
That is the sequence diagram for this code:
package org.testing;
public class A {
static class B
{
C f() {
return new C();
}
}
static class C {
}
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
c = b.f();
}
}

Resources