Twifty:
ES6は、ネストされたクラスをサポートしていませんので、私は親の静的ゲッターに入れ子になったクラスを追加するに連れて行かれました。例えば:
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
}
}
loganfsmyth:
ゲッタープロパティのすべてのアクセスは、まったく新しいクラスを作成しますので、これは失敗している、ちょうどあなたがゲッターにアクセスし、最後の時間を持ったものとすべて同じものを持っていることを起こります。
ネストされたプロパティをしたい場合は、プロパティを使用し、例えば
class Dictionary {
}
Dictionary.Category = class Category {
static is (inst) {
return inst instanceof Category
}
constructor () {}
};