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

  • JavaScript:Moving to ES2015
  • Ved Antani Simon Timms Narayan Prusty
  • 211字
  • 2021-07-09 19:07:47

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.

主站蜘蛛池模板: 辉南县| 廉江市| 奉贤区| 丰原市| 东乌珠穆沁旗| 什邡市| 南投市| 东源县| 德昌县| 蓝山县| 全椒县| 永康市| 准格尔旗| 分宜县| 凌海市| 准格尔旗| 夏河县| 甘洛县| 宜章县| 慈利县| 庆阳市| 江陵县| 会东县| 安泽县| 新乡市| 屯门区| 东阳市| 鹿邑县| 千阳县| 缙云县| 保康县| 陕西省| 定兴县| 淮阳县| 襄城县| 会同县| 江口县| 扬中市| 宝丰县| 泉州市| 胶南市|