【发布时间】:2021-01-12 21:51:26
【问题描述】:
我有一个类Parent,还有一个类Child 扩展Parent。
在Parent 的构造函数中,我现在需要确定x 是原始类的实例还是子类的实例。
就我而言,Parent 实际上是匿名的,我正在使用 instanceof of this.constructor,但它没有按预期工作:
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))
}
}
打电话
new Child().foo()
现在产生 x is instanceof of Parent 但不是 x is instanceof of this.constructor。我做错了什么,如何在不使用 x is instanceof of *Parent* 的情况下解决此问题?
这一切的原因是我包装了我的类定义,这样我就可以在没有new 的情况下创建一个新实例。该类在包装/变异后分配给Parent,因此被包装的类应该是匿名的。
我不知道这是否有意义,我简化的示例可能无法说明所有这些的意义,但除了上面解释的一个问题之外,它实际上非常方便:
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))
}
}
【问题讨论】:
-
我认为
this.constructor是Child而不是Parent。 --- 另外,示例中没有使用super.constructor -
“在我的情况下,父母实际上是匿名的” - 只需解决这个问题,以便您可以编写
instanceof Parent,这就是您想要的并且可以工作。 -
请向我们展示您使用匿名类的实际代码以及为什么需要它来解决您的实际问题。鉴于您之前的问题,似乎这种方法只会导致问题。
-
所以
instanceof Parent会起作用。但是,如果我理解正确,您理想情况下会想写instanceof X?当然,即使目前没有什么能阻止你写const X = (c => { … })(class local { constructor(p) { if (p instanceof local) console.log("got Parent/X instance"); } }); -
"我正在包装我的类定义,这样我就可以在没有 new 的情况下创建一个新实例。" - 这是一个非常基本的包装,我不明白你为什么只复制静态方法。你会想看看the tricks shown/mentioned in this answer。
标签: javascript class oop instanceof