LinkedInAttic/Fiber

Find out the class name instanceof

Opened this issue · 1 comments

Is there a way of finding what Fiber class a variable I have is an instance of?

While JavaScript doesn't natively allow for this (everything's a runtime variable), you may be able to solve what you are trying to do with some sort of class registry:

// the below has not been tested

// definition
var ClassRegistry;
(function() {
  var AsStatic = Fiber.extend(function() {
    return {
      init: function() {
        this.classes = [];
        this.lookup = {};
      },
      register: function(name, klass) {
        this.classes.push(klass);
        this.lookup[this.classes.length - 1] = name;
      },
      getInstance: function(klass) {
        for (var i = 0, len = this.classes.length; i < len; i++) {
          if (klass instanceof this.classes[i]) {
            return this.lookup[i];
          }
        }
      }
    };
  });
  ClassRegistry = new AsStatic();
}());

// usage
var MyClass = Fiber.extend(function() {
  // ...
});
ClassRegistry.register('MyClass', MyClass);

var myClass = new MyClass();

ClassRegistry.getInstance(myClass); // MyClass

In many ways, this may be better as you'll have better control of your use case. Fiber specifically avoids these kinds of features in order to keep the implementation as close to a syntactic sugar layer for native code as possible.

Hope this helps!