I know that in several languages like C++, you can create classes with multiple inheritance (or at least simulate it using interfaces like in Java). In JavaScript, is it possible to define an interface that can be implemented on a class? If so, what would be the best way to approach doing this, ideally incorporating the prototype chain somehow. Would below work, or is there a better way?
function Gizmo() {
console.log('Gizmo constructed');
}
Gizmo.prototype.wamboozle = function () {
console.log('wamboozle');
};
function EventEmitter() {
console.log('EventEmitter constructed');
this.events = {};
}
EventEmitter.prototype.on = function (name, callback) {
this.events[name] ? this.events[name].push(callback) : (this.events[name] = [callback]);
};
EventEmitter.prototype.emit = function (name, event) {
if (this.events[name]) {
this.events[name].forEach(function (callback) {
callback(event);
});
}
};
// set up inheritance and implementation
// maybe this could be a possibility?
Doohickey.prototype = Object.create(Gizmo.prototype);
Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (member) {
Doohickey.prototype[member] = EventEmitter.prototype[member];
});
function Doohickey() {
console.log('Doohickey constructed');
Gizmo.call(this); // initialize base class
EventEmitter.call(this); // initialize interface
}
Doohickey.prototype.turlywoops = function () {
console.log('turlywoops');
};
var myOwnDoohickey = new Doohickey();
// member function works
myOwnDoohickey.turlywoops();
// inherited member function works
myOwnDoohickey.wamboozle();
// interface member functions work
myOwnDoohickey.on('finagle', function (trick) {
console.log(trick);
});
myOwnDoohickey.emit('finagle', {
hello: 'world!'
});
// both true
console.log(myOwnDoohickey instanceof Doohickey);
console.log(myOwnDoohickey instanceof Gizmo);
// don't mind if this isn't necessarily true, though it would be nice
console.log(myOwnDoohickey instanceof EventEmitter);
foo = Object.create(Foo.prototype);,foo instanceof Foo; // truevsfoo = Object.create(Foo);,foo instanceof Foo; // false.