当前位置: 代码网 > it编程>编程语言>Javascript > JavaScript代码优雅,简洁的编写技巧总结

JavaScript代码优雅,简洁的编写技巧总结

2024年05月18日 Javascript 我要评论
1. 强类型检查用===代替 ==// 如果处理不当,它会极大地影响程序逻辑。这就像,你想向左走,但由于某种原因,你向右走0 == false // true0 === false // false2

1. 强类型检查

用===代替 ==

// 如果处理不当,它会极大地影响程序逻辑。这就像,你想向左走,但由于某种原因,你向右走
0 == false // true
0 === false // false
2 == "2" // true
2 === "2" // false
// 例子
const value = "500";
if (value === 500) {
console.log(value);
// 条件不成立,不会进入
}

if (value === "500") {
console.log(value);
// 条件成立,会进入
}

2.变量

用知名其意的方式为变量命名,通过这种方式,当一个人看到它们时,易于搜索和理解。
不好的方式:

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();
// ...
// ...
// ...
// ...
// 当上面代码很多的时候 ,这 `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. 函数

使用长而具有描述性的名称。 考虑到函数表示某种行为,函数名称应该是动词或短​​语,用以说明其背后的意图以及参数的意图。 函数的名字应该说明他们做了什么。
不好的方式:

function notif(user) {
// implementation
}

好的方式:
function notifyuser(emailaddress) {
// implementation
}

避免使用大量参数。 理想情况下,函数应该指定两个或更少的参数。 参数越少,测试函数就越容易,参数多的情况可以使用对象。
不好的方式:

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'
});

使用默认参数替代 || 操作

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

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

一个函数应该只做一件事,不要在一个函数中执行多个操作。

不好的方式:
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设置对象默认值。

不好的方式:
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);

不要使用标志作为参数,因为它们告诉函数做的比它应该做的多。

不好的方式:
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}`);
}

不要污染全局变量。 如果需要扩展现有对象,请使用es类和继承,而不是在原生对象的原型链上创建函数。

不好的方式:
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...
}

尽可能避免条件句,而是使用多态性和继承。

不好的方式:
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中新的语法糖。一切工作就像以前的原型,只是它现在看起来不同,你应该更喜欢他们比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)都使用这种模式。在类中,只需在每个函数的末尾返回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();

总结

这只是改进代码的一小部分。一般生活入,这里所说的原则是人们通常不遵守的原则。他们尝试着去做,但出于各种原因,就没有坚持下去。也许在项目开始时,代码是简洁的,但是当要在截止日期前完成时,这些原则常常被忽略,并被转移到“todo”或“refactor”部分。在这一点上,你的客户更希望您在最后期限之前完成任务,而不是编写简洁的代码。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com