我正在学习如何用JavaScript制作面向对象编程。是否有接口概念(如Java的接口)?

这样我就可以创建一个监听器。


当前回答

这是旧的,但我实现了在ES6上使用的接口,没有转译器。

https://github.com/jkutianski/ES6-Interfaces

其他回答

这是旧的,但我实现了在ES6上使用的接口,没有转译器。

https://github.com/jkutianski/ES6-Interfaces

这是一个老问题,但这个话题一直困扰着我。

由于这里和网络上的许多答案都专注于“强制”界面,我想提出另一种观点:

当我使用行为相似的多个类(即实现一个接口)时,我感到最缺乏接口。

例如,我有一个电子邮件生成器,期望接收电子邮件节工厂,“知道”如何生成节的内容和HTML。因此,它们都需要某种类型的getContent(id)和getHtml(content)方法。

我能想到的最接近接口的模式(尽管它仍然是一种变通方法)是使用一个将获得2个参数的类,它将定义2个接口方法。

这种模式的主要挑战是,方法要么必须是静态的,要么必须获取实例本身作为参数,以便访问其属性。然而,在有些情况下,我发现这种权衡是值得的。

class Filterable { constructor(data, { filter, toString }) { this.data = data; this.filter = filter; this.toString = toString; // You can also enforce here an Iterable interface, for example, // which feels much more natural than having an external check } } const evenNumbersList = new Filterable( [1, 2, 3, 4, 5, 6], { filter: (lst) => { const evenElements = lst.data.filter(x => x % 2 === 0); lst.data = evenElements; }, toString: lst => `< ${lst.data.toString()} >`, } ); console.log('The whole list: ', evenNumbersList.toString(evenNumbersList)); evenNumbersList.filter(evenNumbersList); console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));

在Java中需要接口,因为它是静态类型的,并且在编译期间应该知道类之间的契约。在JavaScript中则不同。JavaScript是动态类型的;这意味着当你获得对象时,你可以检查它是否有特定的方法并调用它。

通过接口,您可以实现一种多态方式。Javascript不需要接口类型来处理这个和其他接口的事情。为什么?Javascript是一种动态类型语言。以具有相同方法的类数组为例:

Circle()
Square()
Triangle()

如果你想知道多态是如何工作的,David krugman linsky的书MFC是很棒的(为c++编写的)。

在这些类中实现draw()方法,将这些类的实例推入数组中,并在迭代数组的循环中调用draw()方法。这是完全正确的。你可以说你隐式地实现了一个抽象类。它不存在于现实中,但在你的脑海中,你做到了,Javascript没有问题。真正的接口的不同之处在于,你必须实现所有的接口方法,在这种情况下,这是不需要的。

接口是一个契约。您必须实现所有的方法。只有让它是静态的,你才需要这样做。

把Javascript这样的语言从动态变成静态是有问题的。静止是不可取的。有经验的开发人员对Javascript的动态特性没有问题。

所以我不清楚使用Typescript的原因。如果你将NodeJS和Javascript结合使用,你可以建立非常高效和经济的企业网站。Javascript/NodeJS/MongoDB组合已经是伟大的赢家。

虽然javaScript中不像Java中那样有接口,但你可以用这条消息下的代码来模仿这种行为。因为接口基本上是一个强制契约,你可以自己构建它。

下面的代码来自3个类:接口、父类和子类。

接口中有检查方法和属性是否存在的方法。 父类用于使用Interface类在子类中强制执行所需的方法和属性。 孩子是父母规则强制执行的类别。

在您正确地设置它之后,如果子程序中缺少方法或属性,那么您将在控制台中看到一个错误,如果子程序正确地实现了契约,则什么也没有。

class Interface {  
    checkRequiredMethods(methodNames) {
        setTimeout( () => {
            const loopLength = methodNames.length;
            let i = 0
            for (i; i<loopLength; i++) {
                if (typeof this[methodNames[i]] === "undefined") {
                    this.throwMissingMethod(methodNames[i]);
                }

                else if (typeof this[methodNames[i]] !== "function") {
                    this.throwNotAMethod(methodNames[i]);
                }
            }
        }, 0);
    }

    checkRequiredProperties(propNames) {
        setTimeout( () => {
            const loopLength = propNames.length;
            let i = 0
            for (i; i<loopLength; i++) {
                if (typeof this[propNames[i]] === "undefined") {
                    this.throwMissingProperty(propNames[i]);
                }

                else if (typeof this[propNames[i]] === "function") {
                    this.throwPropertyIsMethod(propNames[i]);
                }
            }
        }, 0);     
    }

    throwMissingMethod(methodName) {
        throw new Error(`error method ${methodName} is undefined`);
    }

    throwNotAMethod(methodName) {
        throw new Error(`error method ${methodName} is not a method`);
    }

    throwMissingProperty(propName) {
        throw new Error(`error property ${propName} is not defined`);
    }

    throwPropertyIsMethod(propName) {
        throw new Error(`error property ${propName} is a method`);
    }
}
class Parent extends Interface {
    constructor() {
        super()

        this.checkRequiredProperties([
            "p1",
            "p2",
            "p3",
            "p4",
            "p5"
        ]);

        this.checkRequiredMethods([ 
            "m1",
            "m2",
            "m3",
            "m4"
        ]);
    }
}
class Child extends Parent {
    p1 = 0;
    p2 = "";
    p3 = false;
    p4 = [];
    p5 = {};

    constructor() {
        super();
    }

    m1() {}
    m2() {}
    m3() {}
    m4() {}
}
new Child()