欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript代碼優(yōu)雅,簡潔的編寫技巧總結(jié)

 更新時(shí)間:2022年11月14日 22:42:47   投稿:wdc  
專業(yè)開發(fā)人員將為未來的自己和“其他人”編寫代碼,而不僅僅只編寫當(dāng)前能工作就行的代碼。在此基礎(chǔ)上,簡潔代碼可以定義為自解釋的、易于人理解的、易于更改或擴(kuò)展的代碼。以下列表一些好編寫方式,僅供參考

1. 強(qiáng)類型檢查

用===代替 ==

// 如果處理不當(dāng),它會極大地影響程序邏輯。這就像,你想向左走,但由于某種原因,你向右走
0 == false // true
0 === false // false
2 == "2" // true
2 === "2" // false
// 例子
const value = "500";
if (value === 500) {
console.log(value);
// 條件不成立,不會進(jìn)入
}

if (value === "500") {
console.log(value);
// 條件成立,會進(jìn)入
}

2.變量

用知名其意的方式為變量命名,通過這種方式,當(dāng)一個(gè)人看到它們時(shí),易于搜索和理解。
不好的方式:

let daysSLV = 10;
let y = new Date().getFullYear();

let ok;
if (user.age > 30) {
ok = true;
}

好的方式:
const MAX_AGE = 30;
let daysSinceLastVisit = 10;
let currentYear = new Date().getFullYear();

...

const isUserOlderThanAllowed = user.age > MAX_AGE;

不要在變量名中添加額外的不需要的單詞。

不好的方式:
let nameValue;
let theProduct;

好的方式:
let name;
let product;

不要簡寫變量上下文。
不好的方式:
const users = ["John", "Marco", "Peter"];
users.forEach(u => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
// 當(dāng)上面代碼很多的時(shí)候 ,這 `u` 是什么鬼
register(u);
});

好的方式:
const users = ["John", "Marco", "Peter"];
users.forEach(user => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
register(user);
});

不要添加不必要的上下文。
不好的方式:
const user = {
userName: "John",
userSurname: "Doe",
userAge: "28"
};

...

user.userName;

好的方式:
const user = {
name: "John",
surname: "Doe",
age: "28"
};

...

user.name;

3. 函數(shù)

使用長而具有描述性的名稱。 考慮到函數(shù)表示某種行為,函數(shù)名稱應(yīng)該是動詞或短??語,用以說明其背后的意圖以及參數(shù)的意圖。 函數(shù)的名字應(yīng)該說明他們做了什么。
不好的方式:

function notif(user) {
// implementation
}

好的方式:
function notifyUser(emailAddress) {
// implementation
}

避免使用大量參數(shù)。 理想情況下,函數(shù)應(yīng)該指定兩個(gè)或更少的參數(shù)。 參數(shù)越少,測試函數(shù)就越容易,參數(shù)多的情況可以使用對象。
不好的方式:

function getUsers(fields, fromDate, toDate) {
// implementation
}

好的方式:
function getUsers({ fields, fromDate, toDate }) {
// implementation
}

getUsers({
fields: ['name', 'surname', 'email'],
fromDate: '2019-01-01',
toDate: '2019-01-18'
});

使用默認(rèn)參數(shù)替代 || 操作

不好的方式:
function createShape(type) {
const shapeType = type || "cube";
// ...
}

好的方式:
function createShape(type = "cube") {
// ...
}

一個(gè)函數(shù)應(yīng)該只做一件事,不要在一個(gè)函數(shù)中執(zhí)行多個(gè)操作。

不好的方式:
function notifyUsers(users) {
users.forEach(user => {
const userRecord = database.lookup(user);
if (userRecord.isVerified()) {
notify(user);
}
});
}

好的方式:
function notifyVerifiedUsers(users) {
users.filter(isUserVerified).forEach(notify);
}

function isUserVerified(user) {
const userRecord = database.lookup(user);
return userRecord.isVerified();
}

使用Object.assign設(shè)置對象默認(rèn)值。

不好的方式:
const shapeConfig = {
type: "cube",
width: 200,
height: null
};

function createShape(config) {
config.type = config.type || "cube";
config.width = config.width || 250;
config.height = config.height|| 250;
}

createShape(shapeConfig);

好的方式:
const shapeConfig = {
type: "cube",
width: 200
// Exclude the 'height' key
};

function createShape(config) {
config = Object.assign(
{
type: "cube",
width: 250,
height: 250
},
config
);

...
}

createShape(shapeConfig);

不要使用標(biāo)志作為參數(shù),因?yàn)樗鼈兏嬖V函數(shù)做的比它應(yīng)該做的多。

不好的方式:
function createFile(name, isPublic) {
if (isPublic) {
fs.create(`./public/${name}`);
} else {
fs.create(name);
}
}

好的方式:
function createFile(name) {
fs.create(name);
}

function createPublicFile(name) {
createFile(`./public/${name}`);
}

不要污染全局變量。 如果需要擴(kuò)展現(xiàn)有對象,請使用ES類和繼承,而不是在原生對象的原型鏈上創(chuàng)建函數(shù)。

不好的方式:
Array.prototype.myFunc = function myFunc() {
// implementation
};

好的方式:
class SuperArray extends Array {
myFunc() {
// implementation
}
}

4. 條件

避免使用反面條件。

不好的方式:
function isUserNotBlocked(user) {
// implementation
}

if (!isUserNotBlocked(user)) {
// implementation
}

好的方式:
function isUserBlocked(user) {
// implementation
}

if (isUserBlocked(user)) {
// implementation
}

使用條件簡寫。這可能微不足道,但值得一提。僅對布爾值使用此方法,并且如果你確信該值不會是undefined 或null的,則使用此方法。

不好的方式:
if (isValid === true) {
// do something...
}

if (isValid === false) {
// do something...
}

好的方式:
if (isValid) {
// do something...
}

if (!isValid) {
// do something...
}

盡可能避免條件句,而是使用多態(tài)性和繼承。

不好的方式:
class Car {
// ...
getMaximumSpeed() {
switch (this.type) {
case "Ford":
return this.someFactor() + this.anotherFactor();
case "Mazda":
return this.someFactor();
case "McLaren":
return this.someFactor() - this.anotherFactor();
}
}
}

好的方式:
class Car {
// ...
}

class Ford extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() + this.anotherFactor();
}
}

class Mazda extends Car {
// ...
getMaximumSpeed() {
return this.someFactor();
}
}

class McLaren extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() - this.anotherFactor();
}
}

5. 類

class 是JavaScript中新的語法糖。一切工作就像以前的原型,只是它現(xiàn)在看起來不同,你應(yīng)該更喜歡他們比ES5普通功能。

不好的方式:
const Person = function(name) {
if (!(this instanceof Person)) {
throw new Error("Instantiate Person with `new` keyword");
}

this.name = name;
};

Person.prototype.sayHello = function sayHello() { /**/ };

const Student = function(name, school) {
if (!(this instanceof Student)) {
throw new Error("Instantiate Student with `new` keyword");
}

Person.call(this, name);
this.school = school;
};

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.printSchoolName = function printSchoolName() { /**/ };

好的方式:
class Person {
constructor(name) {
this.name = name;
}

sayHello() {
/* ... */
}
}

class Student extends Person {
constructor(name, school) {
super(name);
this.school = school;
}

printSchoolName() {
/* ... */
}
}

使用鏈接。許多庫(如jQuery和Lodash)都使用這種模式。在類中,只需在每個(gè)函數(shù)的末尾返回this就可以將更多的該類方法鏈接到它上。

不好的方式:
class Person {
constructor(name) {
this.name = name;
}

setSurname(surname) {
this.surname = surname;
}

setAge(age) {
this.age = age;
}

save() {
console.log(this.name, this.surname, this.age);
}
}

const person = new Person("John");
person.setSurname("Doe");
person.setAge(29);
person.save();

好的方式:
class Person {
constructor(name) {
this.name = name;
}

setSurname(surname) {
this.surname = surname;
// Return this for chaining
return this;
}

setAge(age) {
this.age = age;
// Return this for chaining
return this;
}

save() {
console.log(this.name, this.surname, this.age);
// Return this for chaining
return this;
}
}

const person = new Person("John")
.setSurname("Doe")
.setAge(29)
.save();

總結(jié)

這只是改進(jìn)代碼的一小部分。一般生活入,這里所說的原則是人們通常不遵守的原則。他們嘗試著去做,但出于各種原因,就沒有堅(jiān)持下去。也許在項(xiàng)目開始時(shí),代碼是簡潔的,但是當(dāng)要在截止日期前完成時(shí),這些原則常常被忽略,并被轉(zhuǎn)移到“TODO”或“REFACTOR”部分。在這一點(diǎn)上,你的客戶更希望您在最后期限之前完成任務(wù),而不是編寫簡潔的代碼。

更多關(guān)于如何優(yōu)雅,簡潔的編寫JavaScript代碼技巧請查看下面的相關(guān)文章

相關(guān)文章

最新評論