前端编程风格

2022/7/9 1:21:20

本文主要是介绍前端编程风格,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

参考:https://es6.ruanyifeng.com/#docs/style

1. let 取代 var
2. let 和 const 之间,优先使用 const
3. const 声明多个变量 const [a, b, c] = [1, 2, 3];
4. 静态字符串一律使用单引号或反引号,动态字符串使用反引号
5. 使用数组成员对变量赋值时,优先使用解构赋值,const [first, second] = arr;
6. 单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾。
7. 对象尽量静态化,不随意添加新属性。如要添加,使用 Object.assign 方法 Object.assign(a, { x: 3 });
8. 定义对象属性和方法,使用简洁表达法
var ref = 'some value';
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
等效于
const atom = {
ref,
value: 1,
addValue(value) {
return atom.value + value;
},
};
9. 使用扩展运算符(...)拷贝数组 (深层次拷贝)
const itemsCopy = [...items];
10. 立即执行函数可以写成箭头函数
(() => {
console.log('123');
})();
11. 匿名函数作参数,使用箭头函数
let arr = [1, 2, 3];
arr = arr.map(x => x * x);
12. 不在使用 self/_this/that 绑定 this
const self = this;
const boundMethod = method.bind(this);
const boundMethod = (...params) => method.apply(this, params);
13. 使用rest 运算符(...)代替 arguments 变量
function concatenateAll(...args) {
return args.join('');
}
14. ES6 模块取代 Node.js 的 CommonJS 语法
使用 import 取代 require()
const moduleA = require('moduleA')
import { func1 } from 'moduleA'
使用 export 取代 module.exports
module.exports = Breadcrumbs;
export default Breadcrumbs;
尽量不用 export default,除非模块只有一个输出值
输出函数首字母小写,输出对象首字母大写
15. 使用 ESLint (太麻烦,酌情考虑)
根目录安装 cnpm install --save-dev eslint
安装 Airbnb 语法规则,以及 import , a11y , react 插件
cnpm install --save-dev eslint-config-airbnb
cnpm install --save-dev eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
根目录新建 .eslintrc
{
"extends": "eslint-config-airbnb"
}

 



这篇关于前端编程风格的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程