TL;DR:
I want to pass object as a parameter when creating a new instance of a class (
ChildClass
)When I'm passing the parameters I want to save the context so
.this
should refer to the object where this instance was creating (not the context of the reference)
parent.class.js
class ParentClass {
constructor(nativeObject, param1, param2) {
this.nativeObject = nativeObject;
this.param1 = param1;
this.param2 = param2;
}
// some logic here
}
module.exports = { ParentClass };
child.class.js
class ChildClass extends ParentClass {
// some logic here
}
module.exports = { ChildClass };
usingclasses.js
let { ChildClass } = require('path/to/my/child/class');
let param1 = 'idkSomeString';
let param2 = 42;
class MyCoolClass {
createChild() {
return new ChildClass(this, param1, param2);
}
}
module.exports = { MyCoolClass };
As you can see I'm passing here this
bc in ParenClass I need to know (that logic is not included in the example) where that instance of the ChildClass was created.
There are many files like usingclasses.js with different classes but each has it's own createChild() method which creates the ChildClass.
What I want to achieve
usingclasses.js
let { ChildClass } = require('path/to/my/child/class');
let paramsObj1 = {
nativeObject: ' ', // ?????,
param1: 'idkSomeString',
param2: 42
};
let paramsObj2 = {
nativeObject: ' ', // ?????,
param1: 'idkSomeString',
param2: 42
};
class MyCoolClass {
createChild() {
return new ChildClass(paramsObj1 );
}
createAnotherChild() {
return new ChildClass(paramsObj2);
}
}
So first question is:
How can I store all the params
in a separate variable (object) at the top
so I can simply do
new ChildClass(objectWithParams1)
,
new ChildClass(objectWithParams2)
...
new ChildClass(objectWithParamsN)
And how can I pass the context (first argument in ParentClass constructor) so it will refer to the object where the instance of this class was created?
I do realize that if I will do
let params = {
nativeObject: this,
param1: 'idkSomeString',
param2: 42
};
this
will refer to the params
object but I need the constructor to know that it was created in the MyCoolClass
UPDATE
After researching I'm curious does .bind
has something do to with this kind of issues. When I actually need to specify what this
is referring to?
Can I somehow specify that this
is referring to MyCoolClass?
This will allow me to store everything at the top and then just pass the one single object as parameter when creating new instance of the ChildClass