【发布时间】:2015-10-01 02:26:06
【问题描述】:
我知道在 C++ 等多种语言中,您可以创建具有多重继承的类(或者至少使用 Java 中的接口模拟它)。在 JavaScript 中,是否可以定义一个可以在类上实现的接口?如果是这样,最好的方法是什么,最好以某种方式合并原型链。下面会起作用吗,还是有更好的方法?
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。 -
@PaulS。已修复,谢谢。
标签: javascript interface prototype multiple-inheritance