JavaScript——编程风格

本篇文章我们将讨论如何将新的语法应用在编码实践当中,与传统的 JavaScript 语法结合在一起,写出合理的、易于阅读和维护的代码。
所谓"编程风格",指的是编写代码的规则。不同的程序员,往往有不同的编程风格。而且这里的风格包括语法上的编程风格和格式上的编程风格。
一.块级作用域let 取代 var - 语法上的编程风格
1.ES6 提出了两个新的声明变量的命令:let和const。
其中,let完全可以取代var,因为两者语义相同,而且let没有副作用。
if (true) {
let x = ‘hello’;
}

for (let y = 0; y <= 10; y++) {
console.log(y);
}


if (true) {
var x = ‘hello’;//全局变量x
}

for (var y = 0; y <= 10; y++) {//全局变量y
console.log(y);
}
上面代码如果用var替代let,实际上就声明了两个全局变量,这显然不是理想的设计方式。变量应该只在其声明的代码块内有效,var命令做不到这一点。

2.var命令存在变量提升效用,let命令没有这个问题。
if (true) {
console.log(x); // ReferenceError引用错误
let x = ‘hello’;
}

if (true) {
console.log(x); // undefined,变量提升
var x = ‘hello’;
}

3.在let和const之间,建议优先使用const,尤其是在全局环境,不应该设置变量,应设置常量。原因是const可以提醒阅读程序的人,这个变量不能改变,比较符合函数式编程思想,并且JavaScript 编译器会对const进行优化,所以多使用const,有利于提高程序的运行效率。
//传统的方式
var a = 1,
b = 2,
c = 3;

//新的方式
const a = 1;
const b = 2;
const c = 3;

//更优的方式
const [a, b, c] = [1, 2, 3];

二、字符串 静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号。
//不建议
const a = “foobar”;
const b = ‘foo’ + a + ‘bar’;

//建议
const a = ‘foobar’;
const b = foo${a}bar;

三.解构赋值
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构
使用数组成员对变量赋值时,优先使用解构赋值。
const arr = [1, 2, 3, 4];
// 不建议
const first = arr[0];
const second = arr[1];

// 建议
const [first, second] = arr;


函数的参数如果是对象的成员,优先使用解构赋值。
// 不建议
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// 建议
function getFullName(obj) {
const { firstName, lastName } = obj;
}
// 建议
function getFullName({ firstName, lastName }) {
}

四.其他操作
1.对象的操作
对象尽量静态化,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用Object.assign方法。
// 不建议
const a = {};
a.x = 3;

// 建议
const a = {};
Object.assign(a, { x: 3 });
// 或者这样
const a = { x: null };
a.x = 3;
对象的属性和方法,尽量采用简洁表达法
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;
},
};
2.使用扩展运算符(…)拷贝数组
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];
console.log(arr1.concat(arr2, arr3)); //[1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log([…arr1, …arr2, …arr3]); //[1, 2, 3, 4, 5, 6, 7, 8, 9]
3.立即执行函数可以写成箭头函数的形式。
(() => {
console.log(‘Welcome to the Internet’);
})();
4.用 Class取代prototype 的操作。因为 Class 的写法更简洁,更易于理解。
// 构造函数+原型
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.showinfo = function() {
return this.name;
}
}

Person.prototype.showinfo = function() {
return this.name + this.age + this.sex
}

// class
class Person {
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
showinfo() {
return this.name
}
}
5.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 个空格。

五.括号的位置 - 语法格式上的编程风格
1.大括号的位置
绝大多数的编程语言,都用大括号({})表示代码块。对于起首的大括号的位置,有许多不同的写法。
最流行的有两种。
第一种是起首的大括号另起一行 - 推荐
block{

}
第二种是起首的大括号跟在关键字的后面,但是Javascript会自动添加句末的分号,有可能会导致一些难以察觉的错误。
//下面的情况就会产生问题。
function fn() {
return
{  
key: value
};
}
2.圆括号
圆括号在Javascript中有两种作用,一种表示调用函数,另一种表示不同的值的组合。我们可以用空格,区分这两
种不同的括号。
调用函数的时候,函数名与左括号之间没有空格。
function fn(){}
fn()
函数名与参数序列之间,没有空格。
function fn(x,y){
return x + y;
}
fn(1,2)
所有其他语法元素与左括号之间,都有一个空格
if (a === 0){…}

3.分号
分号表示语句的结束。大多数情况下,如果你省略了句尾的分号,Javascript会自动添加。
但麻烦的是,如果下一行的第一个符号是下面这五个字符之一,Javascript将不对上一行句尾添加分号:“(”、“[”、“/”、“+“和”-”。

4.相等和严格相等(恒等)
Javascript有两个表示"相等"的运算符:“相等”()和"严格相等"(=)。
因为"相等"运算符会自动转换变量类型(隐式转换),这样写会造成很多意想不到的情况。

所有变量声明都放在函数的头部。
所有函数都在使用之前定义。

*陆荣涛前端学习交流Q群858752519
加群备注:CSDN推荐

猜你喜欢

转载自blog.csdn.net/sdasadasds/article/details/125799555