2

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
  }
}

1 Answer 1

2

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 () {}
};
Sign up to request clarification or add additional context in comments.

3 Comments

That makes sense. I was trying to avoid declaring the property outside of the class due to cluttering a GreaseMonkey script. In Node I would external files. Saying that though, I could add the internal class to window and have the getter return it.
I don't think I understand what you mean by clutter in this context. Why would a getter be more desirable than a property? If you're injecting a script into a page you can always use an IIFE to avoid polluting the global scope while still declaring all your classes next to eachother without nesting.
By clutter, I mean I have a script currently at 6000 lines consisting of about 10 main classes. By having nested classes, I can fold the code in the editor reducing the visible lines to about 40. Also having nested classes makes them easier to find.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.