Fiber icon indicating copy to clipboard operation
Fiber copied to clipboard

Find out the class name instanceof

Open gausie opened this issue 10 years ago • 1 comments

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

gausie avatar Jan 04 '14 08:01 gausie

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!

jakobo avatar Jan 08 '14 06:01 jakobo