Javascript 编码规范(1):Types 和 References

Javascript 4年前 (2020) 互联网
1.4K 0

1、Types

  • 1.1 基本类型: 你可以直接获取到基本类型的值

    const foo = 1;
    let bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
    • Symbols 不能被正确的 polyfill。所以在不能原生支持 symbol 类型的环境[浏览器]中,不应该使用 symbol 类型。
    • string
    • number
    • boolean
    • null
    • undefined
    • symbol
  • 1.2 复杂类型: 复杂类型赋值是获取到他的引用的值。相当于传引用
const foo = [1, 2];
const bar = foo;

bar[0] = 9;

console.log(foo[0], bar[0]); // => 9, 9
  • object
  • array
  • function

2、References

  • 2.1 所有的赋值都用const,避免使用var. eslint: prefer-constno-const-assign

    Why? 因为这个确保你不会改变你的初始值,重复引用会导致bug和代码难以理解

    var a = 1;
    var b = 2;
    
    // good
    const a = 1;
    const b = 2;

    2.2 如果你一定要对参数重新赋值,那就用let,而不是var. eslint: no-var

    Why? 因为let是块级作用域,而var是函数级作用域

    // bad
    var count = 1;
    if (true) {
      count += 1;
    }
    
    // good, use the let.
    let count = 1;
    if (true) {
      count += 1;
    }

    2.3 注意: letconst都是块级作用域

     

版权声明:互联网 发表于 2020-12-24 12:51:56。
转载请注明:Javascript 编码规范(1):Types 和 References | 前端印记
数据库云大使

暂无评论

暂无评论...