有没有办法在ES6 / Node 4中创build接口?

ES6在节点4中是完全可用的。我想知道它是否包含一个定义方法合约的接口的概念,就像在MyClass implements MyInterface

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

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

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

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

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

JavaScript中的devise模式书也可能对你有用:

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

devise模式=类+接口或多inheritance

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