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次。請不要爲語言可能具有的每個功能創建問題。 –