javascript - 有没有办法在ES6 / Node 4中创建接口?

ES6在Node 4中完全可用。我想知道它是否包含定义方法合同的接口概念,如MyClass implements MyInterface

我用谷歌搜索找不到多少,但也许有一个很好的技巧或解决方法可用。

3个解决方案
75 votes

接口不是ES6的一部分,但类是。

如果你真的需要它们,你应该看看支持它们的TypeScript。

gaelgillard answered 2019-08-11T21:43:51Z
8 votes

在评论中debiasej写了下面提到的文章解释了更多关于设计模式(基于接口,类):

[http://loredanacirstea.github.io/es6-design-patterns/]

javascript中的设计模式书也可能对您有用:

[http://addyosmani.com/resources/essentialjsdesignpatterns/book/]

设计模式=类+接口或多重继承

ES6 JS中的工厂模式示例(运行:node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );
42n4 answered 2019-08-11T21:44:52Z
0 votes

有些包可以模拟接口。

你可以使用es6接口

Amit Wagner answered 2019-08-11T21:45:22Z
translate from https://stackoverflow.com:/questions/32626866/is-there-a-way-to-create-interfaces-in-es6-node-4