gpt4 book ai didi

javascript - 通过原型(prototype)链在 JavaScript 中定义接口(interface)

转载 作者:行者123 更新时间:2023-12-02 15:58:57 26 4
gpt4 key购买 nike

我知道在 C++ 等多种语言中,您可以创建具有多重继承的类(或者至少使用 Java 中的接口(interface)来模拟它)。在JavaScript中,是否可以定义一个可以在类上实现的接口(interface)?如果是这样,最好的方法是什么,最好以某种方式合并原型(prototype)链。下面的工作,或者有更好的方法吗?

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);

最佳答案

使用像 underscore.js 这样的东西,您可以基于两个不相关的原型(prototype)创建一个新对象并将其用作原型(prototype)。在此示例中,结果对象中 obj2 中定义的属性/方法将覆盖 obj1 中的任何属性/方法。

function IAmMulti(){

}
IAmMulti.prototype=_.extend(_.clone(Obj1.prototype),_.clone(Obj2.prototype));

以下是一个示例:JavaScript inheritance with _.extend()

关于javascript - 通过原型(prototype)链在 JavaScript 中定义接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com