ES6在节点4中完全可用。我想知道它是否包含定义方法合约的接口概念,如MyClass implements MyInterface
。有没有办法在ES6/Node 4中创建接口?
我找不到很多与我的谷歌搜索,但也许有一个很好的技巧或解决方法可用。
ES6在节点4中完全可用。我想知道它是否包含定义方法合约的接口概念,如MyClass implements MyInterface
。有没有办法在ES6/Node 4中创建接口?
我找不到很多与我的谷歌搜索,但也许有一个很好的技巧或解决方法可用。
接口不是ES6的一部分,但类是。
如果你真的需要它们,你应该看看支持它们的TypeScript。
“他们”是接口。 FWIW您可能需要仔细考虑上面提供的译员链接。不完全如我所料,但接近。 – Berniev
在评论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);
完全? [截至目前没有。](https://kangax.github.io/compat-table/es6/) – Bergi
JS仍然使用[duck typing](https://en.wikipedia.org/wiki/Duck_typing)。没有静态执行的“方法合同”。如果您想动态测试它们,您可以轻松编写自己的界面检查程序。 – Bergi
在ES6上已经有不少书籍可用,例如[这一个](https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20&%20beyond/README.md#you-dont-know-js-es6--beyond) 。如果你阅读其中的一个,你不必再想知道什么功能,并且在ES6中不可用。在最坏的情况下[看规格](http://www.ecma-international.org/ecma-262/6.0/index.html)。术语“界面”出现12次。请不要为语言可能具有的每个功能创建问题。 –