由于 es6 不支持嵌套类,因此我开始将嵌套类添加到父级的静态 getter 中。例如:
class Dictionary {
static get Category () {
return class Category {
static is (inst) {
return inst instanceof Category
}
constructor () {}
}
}
}
但是,我在 instanceof
方面遇到了问题。我想确保给定的变量是正确的实例。
const test = new Dictionary.Category()
const ctor = Dictionary.Category
console.log(test instanceof Dictionary.Category) // false
console.log(Dictionary.Category.is(test)) // false
console.log(test instanceof ctor) // false
console.log(test.__proto__.constructor === ctor) // false
console.log(test.constructor === ctor) // false
console.log(test.constructor, ctor) // both function Category()
console.log(new Dictionary() instanceof Dictionary) // true (sanity check)
到目前为止,我一直在测试 constructor.name
但这是有限的。我该如何解决这个问题?
感谢下面的答案指出了问题,这是一个可行的解决方案:
class Dictionary {
static get Category () {
Dictionary.__Category = Dictionary.__Category || class Category {
constructor () {}
}
return Dictionary.__Category
}
}
最佳答案
这是失败的,因为每次访问 getter 属性都会创建一个全新的类,它恰好具有与上次访问 getter 时获得的所有相同的内容。
如果您想要嵌套属性,请使用属性,例如
class Dictionary {
}
Dictionary.Category = class Category {
static is (inst) {
return inst instanceof Category
}
constructor () {}
};
关于javascript - 将instanceof与从函数返回的类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60733541/