官术网_书友最值得收藏!

ECMAScript 2015 classes and modules

We've seen so far that it is perfectly possible to build classes and even modules in pre ECMAScript -2015 JavaScript. The syntax is, obviously, a bit more involved than in a language such as C# or Java. Fortunately ECMAScript-2015, brings support for some syntactic sugar for making classes:

class Castle extends Westeros.Structures.BaseStructure {
  constructor(name, allegience) {
    super(name);
    ...
  }
  Build() {
    ...
    super.Build();
  }
}

ECMAScript-2015 also brings a well thought out module system for JavaScript. There's also syntactic sugar for creating modules which looks like this:

module 'Westeros' {
  export function Rule(rulerName, house) {
    ...
    return "Long live " + rulerName + " of house " + house;
  }
}

As modules can contain functions they can, of course, contain classes. ECMAScript-2015 also defines a module import syntax and support for retrieving modules from remote locations. Importing a module looks like this:

import westeros from 'Westeros';
module JSON from 'http://json.org/modules/json2.js';
westeros.Rule("Rob Stark", "Stark");

Some of this syntactic sugar is available in any environment which has full ECMAScript-2015 support. At the time of writing, all major browser vendors have very good support for the class portion of ECMAScript-2015 so there is almost no reason not to use it if you don't have to support ancient browsers.

主站蜘蛛池模板: 青川县| 邵阳市| 昭觉县| 宁国市| 嘉善县| 曲周县| 民勤县| 资源县| 电白县| 惠安县| 旅游| 松阳县| 平谷区| 佛山市| 平谷区| 洛川县| 丰顺县| 辛集市| 永州市| 石泉县| 桐庐县| 浠水县| 佛山市| 英超| 栾川县| 榕江县| 漳平市| 临泉县| 河间市| 龙州县| 肥东县| 巴林右旗| 灌南县| 临安市| 克什克腾旗| 桃江县| 花垣县| 常德市| 阿荣旗| 江源县| 芮城县|