ECMAScript6 coding specification

Posted by shibiny on Wed, 19 Jan 2022 17:02:56 +0100

Normative content

statement

  • 1.1 variables

    For variables that are only valid in the current scope, let should be used instead of var. for global variable declaration, VAR should be used, but too many global variables should be declared to avoid polluting the environment

    // Not good
    const variables; 
    const globalObj = null; // Not defining a constant
    let globalObj = null; 
    
    for (var i=0; i<5; i++) {
      console.log(i);
    }
    console.log(i);
    
    // good
    let variables;
    var globalObj = null; 
    
    for (let i=0; i<5; i++) {
      console.log(i);
    }
    console.log(i);
    
  • 1.2 constants

    Const shall be used to declare constants, and the naming shall follow the popular convention of all uppercase letters. Const shall be used to declare immutable data. Note: const and let are only valid in the block level scope where the declaration is located

    // Not good
    const someNum = 123;
    const AnotherStr = 'Invariant string';
    let SOME_ARR = ['no','change','number','group'];
    var ANOTHER_OBJ = {
      'Invariant object': true
    };
    
    // good
    const SOME_NUM = 123;
    const ANOTHER_STR = 'Invariant string';
    const SOME_ARR = ['no','change','number','group'];
    const ANOTHER_OBJ = {
      'Invariant object': true
    };
    

character string

  • 2.1 template string

    For multi line works, the code is easier to write with the signature character password of the label (`) represented by the situation of the works and the situation of the works

    // Not good
      const  multiStr  =  'Multiline string wrapping representation,\\n This is a new line.' ; 
      function  sayHi ( name )  { 
        return  'how are you,'  +  name  +  '?' ; 
      } 
    
      // good
      const  multiStr  =  `Multiline string wrapping representation,
                      This is a new line.` ; 
      function  sayHi ( name )  { 
        return  `how are you, ${ name }?` ; 
      }
    

deconstruction

  • 3.1 the number of layers of class 3 objects in class structure cannot exceed the number of layers

    // Not good
    let obj = {
      'one': [
        { 'newTwo': [
            { 'three': [
                'four': 'Too many layers, dizzy'
              ]
            }
          ]
      ]
    };
    
    // good
    let obj = {
      'one': [
        'two',
        {'twoObj': 'Clear structure' }
      ]
    };
    
  • 3.2 parentheses are not used in Deconstruction statements

    // Not good
    [(a)] = [11]; // a undefined
    let { a: (b) } = {}; // Parsing error
    
    // good
    let [a, b] = [11, 22];
    
  • 3.3 object deconstruction

    The object deconstruction element has nothing to do with the order. When the default value is specified for the object, it only takes effect when it is identical to undefined (! = = null)

    • 3.3.1 if the function parameter is an object, the object deconstruction assignment is used

      // Not good
      function someFun(opt) {
        let opt1 = opt.opt1;
        let opt2 = opt.opt2;
        console.log(op1);
      }
      
      // good
      function someFun(opt){
        let {opt1, opt2} = opt;
        console.log( `$(opt1) add $(opt2)` );
      }
      
      function someFun( {opt1, opt2} ){
        console.log(opt1);
      }
      
    • 3.3.2 if the function has multiple return values, use object deconstruction instead of array deconstruction to avoid the problem of adding order

      // Not good
      function anotherFun(){
        const one = 1, two = 2, three = 3;
        return [one, two, three];
      }
      
      const [one, three, two] = anotherFun(); // The order is out of order
      
      // good
      function anotherFun(){
        const one = 1, two = 2, three = 3;
        return { one, two, three };
      }
      
      const { one, three, two } = anotherFun(); // Never mind the order
      
    • 3.3.3 declared variables cannot be used for deconstruction assignment (syntax error)

      // syntax error
      let a;
      {a} = {a: 123};
      
  • 3.4 array deconstruction

    Array elements are order dependent

    • 3.4.1 values of exchange variables

      let x = 1;
      let y = 2;
      
      // Not good
      let temp;
      temp = x;
      x = y;
      y = temp;
      
      // good
      [x, y] = [y, x]; // Exchange variable
      
    • 3.4.2 array deconstruction is used when assigning array members to variables

      const arr = [1,2,3,4,5];
      
      // Not good
      const one = arr[0];
      const two = arr[1];
      
      // good
      const [one, two] = arr;
      

array

  • 4.1 convert array like objects and traversable objects (such as Set and Map) into real arrays

    Use array Convert from

    // Not good
    function foo(){
      let args = Array.prototype.slice.call(arguments);
    }
    
    // good
    function foo(){
      let args = Array.from(arguments);
    }
    
  • 4.2 array de duplication

    Combine Set structure with array from

    // Not good
    // The use of indexOf, HashTable and other forms is not concise and clear enough
    
    // good
    function deduplication(arr){
      return Array.from(new Set(arr));
    }
    
  • 4.3 array copy

    Extend with array form

    const items = [1,2,3];
    
    // Not good
    const len = items.length;
    let copyTemp = [];
    for (let i=0; i<len; i++) {
      copyTemp[i] = items[i];
    }
    
    // good
    let copyTemp = [...items];
    
  • 4.4 converting a set of values into an array

    Use array Of for conversion

    // Not good
    let arr1 = new Array(2); // [undefined x 2]
    let arr2 = new Array(1,2,3); // [1, 2, 3]
    
    // good
    let arr1 = Array.of(2);  // [2]
    let arr2 = Array.of(1,2,3); // [1, 2, 3]
    

function

  • 5.1 when you want to use function expressions or anonymous functions, use arrow functions

    The arrow function is more concise and bound to this

    // Not good
    const foo = function(x){
      console.log('There is a function promotion problem');
      console.log(foo.name); // Return '', the function expression is unnamed, and the function declaration can be
    };
    
    [1, 2, 3].forEach(function(x){
      return x + 1;
    });
    
    // good
    const foo = x => {
      console.log('There is no function promotion problem');
      console.log(foo.name); // Return to 'foo'
    };
    
    [1, 2, 3].forEach( x => {
      return x + 1;
    });
    
    • 5.1.1 writing convention of arrow function

      When the function body has only a single line statement, it is allowed to write on the same line and remove the curly braces. When the function has only one parameter, it is allowed to remove the braces outside the parameter

      // good
      const foo = x => x + x; // Note that return x + x will be the default here. If there are curly bracket statement blocks, return will not be used
      
      [1, 2, 3].map(x => x * x);
      
    • 5.1.2 use the arrow function to return an object and wrap it in parentheses

      // Not good
      let test = x => {x:x}; // Curly braces become statement blocks and do not represent objects
      
      // good
      let test = x => ({x:x}); // Use parentheses to correctly return {x:x}
      
  • 5.2 call function IIFE immediately

    Use arrow function

    // Not good
    (function(){
      console.log('Ha');
    })();
    
    // good
    (() => {
      console.log('Ha');
    })();
    
  • 5.3 use rest syntax instead of {arguments replace

    The rest parameter is a real array and does not need to be converted. Note: the arguments object cannot be used in the arrow function

    // Not good
    function foo(){
      let args = Array.prototype.slice.call(arguments);
      return args.join('');
    }
    
    // good
    function foo(...args) {
      return args.join('');
    }
    
  • 5.4 specifying default values for function parameters

    The default parameter assignment syntax of the function is adopted

    // Not good
    function foo(opts) {
      opts = opts || {};// There is a side effect of converting false values such as 0 and '' into default values
    }
    
    // good
    function foo( opts = {}) {
      console.log('More concise and safe');
    }
    
  • 5.5 function methods in objects use abbreviations

    // Not good
    const shopObj = {
      des: 'Object module writing',
      foo: function(){
        console.log('Methods in objects');
      }
    };
    
    // good
    const shopObj = {
      des: 'Object module writing',
      foo(){
        console.log('Methods in objects');
      }
    };
    

class

  • 6.1 the class name shall be written in Pascal cased
class SomeClass{
}
  • 6.2 when defining classes, the order of methods is as follows:

    • constructor
    • Public get/set is a public accessor. Set can only pass one parameter
    • Public methods public methods, distinguished by function names, without underscores
    • Private , get/set , private accessors, private related names should be underlined_ Prefix
    • Private methods
    class SomeClass {
      constructor() {
        // constructor
      }
      
      get aval() {
        // public getter
      }
      
      set aval(val) {
        // public setter
      }
      
      doSth() {
        // Common method
      }
      
      get _aval() {
        // private getter
      }
      
      set _aval() {
        // private setter
      }
      
      _doSth() {
        // Private method
      }
    }
    
  • 6.3 if it is not a class, do not use new

    // Not good
    function Foo() {
    }
    const foo = new Foo();
    
    // good
    class Foo() {
    }
    const foo = new Foo();
    
  • 6.4 use the real Class writing method, and do not use prototype for simulation extension

    Class is more concise and easy to maintain

    // Not good
    function Dog(names = []) {
      this._names = [...names];
    }
    Dog.prototype.bark = function(){
      const currName = this._names[0];
      alert(`one one ${currName}`);
    }
    
    // good
    class Dog {
      constructor(names = []){
        this._name = [...names];
      }
      bark() {
        const currName = this._names[0];
        alert(`one one ${currName}`);
      }
    }
    
  • 6.5 class should be defined before use

    Although there is no hoist problem with classes in the specification, conversion tools such as babel only convert to function expressions. There is still hoist here. When using inheritance, you should define the parent class first and then the child class

    // Not good
    let foo = new Foo();
    class Foo { } 
    
    // good
    class Foo { }
    let foo = new Foo();
    
    class SubFoo extends Foo {
      
    }
    
  • 6.6 precautions for this

    When subclasses use the super keyword, this can only be used after super is called. You can use return this in the method to realize the chain call writing method

    class Foo {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      }
    }
    
    // Not good
    class SubFoo extends Foo {
      constructor(x, y, z) {
        this.z = z; // Reference error
        super(x, y);
      }
    }
    
    // good
    class SubFoo extends Foo {
      constructor(x, y, z) {
        super(x, y);
        this.z = z; // this is called after super.
      }
      setHeight(height) {
        this.height = height;
        return this;
      }
    }
    

modular

  • 7.1 use import / export to load and export modules, and do not use non-standard module writing

    // Not good
    const colors  = require('./colors');
    module.exports = color.lightRed;
    
    // good
    import { lightRed } from './colors';
    export default lightRed;
    
  • 7.2 ensure that each module has and has only one default export module

    // Not good
    const lightRed = '#F07';
    
    export lightRed;
    
    // good
    const lightRed = '#F07';
    export default lightRed;
    
  • 7.3 import: do not use the unified character * ` ` for overall import

    // Not good
    import * as colors from './colors';
    
    // good
    import colors from './colors';
    
  • 7.4 do not mix import and export in one line

    Separate import and export to make the structure clearer and more readable

    // Not good
    export { lightRed as default } from './colors';
    
    // good
    import { lightRed } from './colors';
    export default lightRed;
    
  • 7.5 object deconstruction form shall be adopted when multivariable is to be exported

    export is placed at the bottom to make the variables to be exported clearer

    // Not good
    export const lightRed = '#F07';
    export const black  = '#000';
    export const white  = '#FFF';
    
    // good
    const lightRed = '#F07';
    const black  = '#000';
    const white  = '#FFF';
    
    export default { lightRed, black, white };
    

GitHub - Su ven / ES6 coding style: ECMAScript 2015 coding specification - front end team of GF Securities

Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.https://serious-lose.notion.site/ECMAScript6-74312f0e8fac47e2983616ca0f2a1d4d

Topics: Javascript Front-end Vue.js Other