es6 grammar was released in June 2015. es6 is the JavaScript language standard officially released in June 2015. It is officially called ECMAScript2015 (ES2015). It is the sixth version of ECMAScript. The goal of es6 is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The full name of es6 is ECMAScript6 (the 6th version of ECMAScript). It is a standard for the JavaScript language officially released in June 2015. It is officially called ECMAScript. 2015 (ES2015). Its goal is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language.
ECMAScript 6 has basically become the industry standard, and its popularity is much faster than ES5. The main reason is that modern browsers support ES6 very quickly, especially Chrome and Firefox browsers, which already support ES6. most features.
ECMAScript is a universal scripting language implemented according to the ECMA-262 standard. The ECMA-262 standard mainly stipulates the syntax, types, statements, keywords, reserved words, operators, objects, etc. of this language. Several parts, the latest version of ECMAScript is ECMAScript6 (referred to as "ES6").
Every time you see ES followed by a number, it is a different version of ECMAScript.
ECMAScript6 is the 6th version of ECMAScript, so it can be referred to as es6.
The development history of ECMAScript 6
In 2000, ECMAScript 4.0 began to be brewed. This version did not pass in the end, but most of its contents were inherited by ECMAScript6. Therefore, the starting point for the formulation of ECMAScript6 was actually 2000.
In October 2007, the ECMAScript 4.0 draft was released, and the official version was originally expected to be released in August 2008. However, there are serious differences between the parties on whether to adopt this standard. Large companies, led by Yahoo, Microsoft, and Google, oppose major upgrades to JavaScript and advocate minor changes; Mozilla, headed by JavaScript creator Brendan Eich, insists on the current draft.
In July 2008, because there were too many differences between the parties and the debate was too fierce about which functions should be included in the next version, ECMA decided to suspend the development of ECMAScript 4.0 at a meeting and remove some of the aspects involved in improving existing functions. A small part was released as ECMAScript 3.1, while other radical ideas were expanded and put into later versions. Due to the atmosphere of the conference, the project codename of this version was Harmony. Shortly after the meeting, ECMAScript 3.1 was renamed ECMAScript 5.
In December 2009, ECMAScript 5.0 was officially released. The Harmony project was divided into two. Some more feasible ideas were named JavaScript.next and continued to be developed, and later evolved into ECMAScript 6; some less mature ideas were regarded as JavaScript.next.next and will be developed in the further future. Consider launching again.
In 2011, after the release of ECMAScript 5.1, the development of version 6.0 began.
In March 2013, the ECMAScript 6 draft was frozen and no new features were added. New functionality is envisioned to be put into ECMAScript 7.
In December 2013, the ECMAScript 6 draft was released. This will then be followed by a 12-month discussion period to hear feedback from all parties. Because this version introduces too many grammatical features, and during the formulation process, many organizations and individuals continue to submit new features. The standards committee finally decided that the standard would be officially released once every June as the official version of that year. In the following time, changes will be made based on this version. Until June of the next year, the draft will naturally become the new year's version.
In June 2015, ECMAScript 6 (ES6) was officially adopted and became an international standard. The official name is "ECMAScript 2015" (ES2015 for short).
The first version of ES6 was released in June 2015, and its official name is "ECMAScript 2015 Standard" (ES2015 for short). In June 2016, the slightly revised "ECMAScript 2016 Standard" (ES2016 for short) was released as scheduled. This version can be regarded as the ES6.1 version, because the difference between the two is very small (only the includes method and index of the array instance are added) operator), basically the same standard.
Therefore, ES6 is both a historical term and a general term. It means the next generation standard of JavaScript after version 5.1, covering ES2015, ES2016, ES2017, etc., while ES2015 is the official name, specifically referring to The official version of the language standard released that year. When ES6 is mentioned in this book, it usually refers to the ES2015 standard, but sometimes it also refers to the "next generation JavaScript language" in general.
Discuss how to apply the new syntax of ES6 to coding practice and combine it with traditional JavaScript syntax to write reasonable, Code that is easy to read and maintain.
Block-level scope
(1)let replaces var
ES6 proposes two There are two new commands for declaring variables: let
and const
. Among them, let
can completely replace var
, because the semantics of the two are the same, and let
has no side effects.
'use strict'; if (true) { let x = 'hello'; } for (let i = 0; i < 10; i++) { console.log(i); }
If var
is used instead of let
in the above code, two global variables are actually declared, which is obviously not the intention. Variables should only be valid within the code block in which they are declared. The var
command cannot do this. The
var
command has variable promotion effect, but the let
command does not have this problem.
'use strict'; if (true) { console.log(x); // ReferenceError let x = 'hello'; }
If var
is used instead of let
in the above code, the line console.log
will not report an error, but will output undefined
because the variable declaration is hoisted to the head of the code block. This violates the principle of variables being declared first and used later.
Therefore, it is recommended that you no longer use the var
command, but use the let
command instead.
(2) Global constants and thread safety
Between let
and const
, it is recommended to use ## first #const, especially in the global environment, variables should not be set, only constants.
const is better than
let for several reasons. One is
const, which can remind people who read the program that this variable should not be changed; the other is
const, which is more in line with the idea of functional programming. The operation does not change the value, but only creates a new value, and this It is also beneficial to future distributed computing; the last reason is that the JavaScript compiler will optimize
const, so using
const more will help improve the running efficiency of the program, that is to say The essential difference between
let and
const is actually the different internal processing of the compiler.
// bad var a = 1, b = 2, c = 3; // good const a = 1; const b = 2; const c = 3; // best const [a, b, c] = [1, 2, 3];
constThere are two benefits of declaring constants. First, people reading the code will immediately realize that the value should not be modified. Second, it prevents errors caused by inadvertently modifying the variable value. mistake.
let should only appear in single threads. Code run by threads cannot be shared by multiple threads, which will help ensure thread safety.
String
Static strings always use single quotes or backticks, and do not use double quotes. Dynamic strings use backticks.// bad const a = "foobar"; const b = 'foo' + a + 'bar'; // acceptable const c = `foobar`; // good const a = 'foobar'; const b = `foo${a}bar`;
Destructuring assignment
When using array members to assign values to variables, destructuring assignment is preferred.const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
// bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; } // good function getFullName(obj) { const { firstName, lastName } = obj; } // best function getFullName({ firstName, lastName }) { }
// bad function processInput(input) { return [left, right, top, bottom]; } // good function processInput(input) { return { left, right, top, bottom }; } const { left, right } = processInput(input);
Object
Object defined in a single line, the last member does not end with a comma. For objects defined on multiple lines, the last member ends with a comma.// bad const a = { k1: v1, k2: v2, }; const b = { k1: v1, k2: v2 }; // good const a = { k1: v1, k2: v2 }; const b = { k1: v1, k2: v2, };
Object.assign method.
// bad const a = {}; a.x = 3; // if reshape unavoidable const a = {}; Object.assign(a, { x: 3 }); // good const a = { x: null }; a.x = 3;
// bad const obj = { id: 5, name: 'San Francisco', }; obj[getKey('enabled')] = true; // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, };
obj needs to be calculated. At this time, it is best to use attribute expressions, and define this attribute together with other attributes when creating a new
obj. This way, all properties are defined in one place.
var ref = 'some value'; // bad const atom = { ref: ref, value: 1, addValue: function (value) { return atom.value + value; }, }; // good const atom = { ref, value: 1, addValue(value) { return atom.value + value; }, };
Array
Copy an array using the spread operator (...).// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo);
Function
The immediate execution function can be written in the form of an arrow function.(() => { console.log('Welcome to the Internet.'); })();
// bad [1, 2, 3].map(function (x) { return x * x; }); // good [1, 2, 3].map((x) => { return x * x; }); // best [1, 2, 3].map(x => x * x);
Function.prototype.bind, self/_this/that should no longer be used to bind this.
// bad const self = this; const boundMethod = function(...params) { return method.apply(self, params); } // acceptable const boundMethod = method.bind(this); // best const boundMethod = (...params) => method.apply(this, params);
// bad function divide(a, b, option = false ) { } // good function divide(a, b, { option = false } = {}) { }
// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
// bad function handleThings(opts) { opts = opts || {}; } // good function handleThings(opts = {}) { // ... }
Map structure
Note to distinguish between Object and Map. Use Object only when simulating entity objects in the real world. If you only need the data structure ofkey: value, use the Map structure. Because Map has a built-in traversal mechanism.
let map = new Map(arr); for (let key of map.keys()) { console.log(key); } for (let value of map.values()) { console.log(value); } for (let item of map.entries()) { console.log(item[0], item[1]); }
Class
总是用 Class,取代需要 prototype 的操作。因为 Class 的写法更简洁,更易于理解。
// bad function Queue(contents = []) { this._queue = [...contents]; } Queue.prototype.pop = function() { const value = this._queue[0]; this._queue.splice(0, 1); return value; } // good class Queue { constructor(contents = []) { this._queue = [...contents]; } pop() { const value = this._queue[0]; this._queue.splice(0, 1); return value; } }
使用extends
实现继承,因为这样更简单,不会有破坏instanceof
运算的危险。
// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function() { return this._queue[0]; } // good class PeekableQueue extends Queue { peek() { return this._queue[0]; } }
模块
首先,Module 语法是 JavaScript 模块的标准写法,坚持使用这种写法。使用import
取代require
。
// bad const moduleA = require('moduleA'); const func1 = moduleA.func1; const func2 = moduleA.func2; // good import { func1, func2 } from 'moduleA';
使用export
取代module.exports
。
// commonJS的写法 var React = require('react'); var Breadcrumbs = React.createClass({ render() { return <nav />; } }); module.exports = Breadcrumbs; // ES6的写法 import React from 'react'; class Breadcrumbs extends React.Component { render() { return <nav />; } }; export default Breadcrumbs;
如果模块只有一个输出值,就使用export default
,如果模块有多个输出值,就不使用export default
,export default
与普通的export
不要同时使用。
不要在模块输入中使用通配符。因为这样可以确保你的模块之中,有一个默认输出(export default)。
// bad import * as myObject from './importModule'; // good import myObject from './importModule';
如果模块默认输出一个函数,函数名的首字母应该小写。
function makeStyleGuide() { } export default makeStyleGuide;
如果模块默认输出一个对象,对象名的首字母应该大写。
const StyleGuide = { es6: { } }; export default StyleGuide;
ESLint 的使用
ESLint 是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。
首先,在项目的根目录安装 ESLint。
$ npm install --save-dev eslint
然后,安装 Airbnb 语法规则,以及 import、a11y、react 插件。
$ npm install --save-dev eslint-config-airbnb $ npm install --save-dev eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
最后,在项目的根目录下新建一个.eslintrc
文件,配置 ESLint。
{ "extends": "eslint-config-airbnb" }
现在就可以检查,当前项目的代码是否符合预设的规则。
index.js
文件的代码如下。
var unused = 'I have no purpose!'; function greet() { var message = 'Hello, World!'; console.log(message); } greet();
使用 ESLint 检查这个文件,就会报出错误。
$ npx eslint index.js index.js 1:1 error Unexpected var, use let or const instead no-var 1:5 error unused is defined but never used no-unused-vars 4:5 error Expected indentation of 2 characters but found 4 indent 4:5 error Unexpected var, use let or const instead no-var 5:5 error Expected indentation of 2 characters but found 4 indent ✖ 5 problems (5 errors, 0 warnings)
上面代码说明,原文件有五个错误,其中两个是不应该使用var
命令,而要使用let
或const
;一个是定义了变量,却没有使用;另外两个是行首缩进为 4 个空格,而不是规定的 2 个空格。
【相关推荐:javascript视频教程、编程视频】
The above is the detailed content of When was es6 syntax released?. For more information, please follow other related articles on the PHP Chinese website!