I got a class Parent
, and a class Child
extending Parent
.
In Parent
's constructor I need now to determine if x
is an instance of the original class or of the child class.
As in my case Parent
is actually anonymous I'm using instanceof of this.constructor
which isn't working as expected:
class Parent {
constructor(x) {
if (x instanceof this.constructor) {
console.log("x is instanceof of this.constructor");
}
if (x instanceof Parent) {
console.log("x is instanceof of Parent");
}
}
}
class Child extends Parent {
constructor(x) {
super(x);
}
foo(x) {
new this.constructor(new super.constructor(x))
}
}
Calling
new Child().foo()
now yields x is instanceof of Parent
but not x is instanceof of this.constructor
. What am I doing wrong and how can I fix this without using x is instanceof of *Parent*
?
The reason for all this is that I'm wrapping my class definition so that I can create a new instance without new
. The class is assigned to Parent
after wrapping/mutating, so the class that is wrapped should be anonymous.
I don't know if that makes any sense, and my reduced example may fail to make clear what's the point of all this, but apart from the one issue explained above it's actually quite handy:
X() // create new instance of Parent without new
X.f // access static methods
const { X, c: Parent } = function (c) {
return {
X: Object.assign(
function () {
return new c(...arguments);
},
_.pick(c, Object.getOwnPropertyNames(c) // using lodash here
.filter(n => typeof c[n] === "function")
)
),
c
};
}(class {
constructor(x) {
if (x instanceof this.constructor) {
console.log("x is instanceof of this.constructor");
}
if (x instanceof Parent) {
console.log("x is instanceof of Parent");
}
}
})
class Child extends Parent {
constructor(x) {
super(x);
}
foo(x) {
new this.constructor(new super.constructor(x))
}
}