using instanceof with class returned from a function

Twifty :

Since es6 doesn't support nested classes, I've taken to adding a nested class to a static getter of the parent. For example:

class Dictionary {
  static get Category () {
    return class Category {
      static is (inst) {
        return inst instanceof Category
      }
      constructor () {}
    }
  }
}

However, I'm having a problem with instanceof. I want to make sure a given variable is a correct instance.

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)

Up till now, I've been testing the constructor.name but this is limited. How can I solve this problem?

Thanks to the answer below pointing out the problem, here is a working solution:

class Dictionary {
  static get Category () {
    Dictionary.__Category = Dictionary.__Category || class Category {
      constructor () {}
    }
    return Dictionary.__Category
  }
}
loganfsmyth :

This is failing because every access of the getter property creates a whole new class, it just happens to have all the same stuff as the one you got last time you accessed the getter.

If you want a nested property, use a property, e.g.

class Dictionary {
}
Dictionary.Category = class Category {
  static is (inst) {
    return inst instanceof Category
  }
  constructor () {}
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301844&siteId=1
Recommended