4

I'd like to check if the object x implements (is instance of) the mixin MyInterface:

Ext.define('MyInterface', {
    interfaceMethod: Ext.emptyFn
});

Ext.define('Foo', {
    mixins: {
        myInterface: 'MyInterface'
    }
});

var x = new Foo();

doesn't work work:

console.log(x instanceof MyInterface);

ugly workaround:

var isInstanceOfMyInterface = false;
for (var i in x.mixins) {
    if (x.mixins[i].$className == 'MyInterface') {
        isInstanceOfMyInterface = true;
    }
}
console.log(isInstanceOfMyInterface);

The workaround has one major issue: it doesn't work if a subclass of MyInterface is used.

jsfiddle

Niko Sams
  • 4,304
  • 3
  • 25
  • 44
  • A pattern used in the core is to add some identifying property on a class or mixin that can be checked. So for example add an `isMyInterface` property on the interface which then gets mixed into `Foo`. – Evan Trimboli May 30 '14 at 06:33
  • That's it - thanks - please create an answer for that so I can accept it. – Niko Sams May 30 '14 at 07:31

2 Answers2

5

A pattern the Ext core uses is to apply a mixin specific property so you can test for its existence. It's a lot cheaper than an instanceof check as well. For example:

Ext.define('MyInterface', {
    isMyInterface: true,
    interfaceMethod: Ext.emptyFn,
});

Ext.define('Foo', {
    mixins: {
        myInterface: 'MyInterface'
    }
});

var x = new Foo();
console.log(x.isMyInterface);
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
0

Mixins solve the problem of multiple inheritance because there is no way to make class C inherit from both A and B in plain JavaScript. The logic is then let class C to inherit from A and use class B as mixin. The mixin B is a sort of repository of additional methods and properties for C.

When the mixin B is used in class C, all its methods and properties are copied to the prototype of C and when C is instantiated it contains its own methods, methods of A, because it inherits from A, and B because mixin's methods are added to it.

Also, C can use more than one mixin to add additional methods/properties. Using mixin does not change the class name of the target class, C stays C.

Internally in Ext used mixins are held as object in mixins object of the target class as name/value pairs.

Summed together, your way is already the fine way to check if a class uses a mixin, nevetheless, it can be improved:

  1. you can implement the above code as a method of the class(es) you want to check
  2. you can break the above look once the mixin is found to save some cycles
Saki
  • 5,827
  • 2
  • 15
  • 15