JavaScript 书写规范及技巧

强类型检查

使用 === 而不是 ==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0 == false // true 
0 === false // false
2 == "2" // true
2 === "2" // false

// example
const val = "123";
if (val === 123) {
console.log(val);
// it cannot not be reached
}
if (val === "123") {
console.log(val);
// it can be reached
}

变量命名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 不推荐
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;

设置原型的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Person(name) {
this.name = name;
}


function Student(name) {
Person.call(this, name);
}

Student.prototype = Object.create(Person.prototype);
// Student 的原型会被设置为 Person。

// 实际上想要将 Student 的原型设置为 Student。
// 需要这么写
Student.prototype.constructor = Student;

// 或者
class Student extends Person {
}

创建 Web Workers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script id="worker" type="javascript/worker">
self.onmessage = (e) => {
self.postMessage('msg');
};
</script>
<script>
const blob = new Blob([
document.querySelector('#worker').textContent
]);

const worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = (e) => {
console.log(e.data);
}
worker.postMessage("hello");
</script>

map 技巧

map 里使用 parseInt 会返回 NaN

1
2
3
4
5
6
//  不要这么写
['1','2','3'].map(parseInt)

// 可以
['1','2','3'].map(Number)
['1','2','3'].map(num => parseInt(num, 10))

三目运算符

1
2
3
4
5
// 当 x === 1 返回 false 不想调用 doSomethingElse 时
x === 1 ? doSomething() : doSomethingElse();

// 可以
x === 1 && doSomething();

清除 Yarn 中的缓存

1
yarn cache clear

innerText 在 IE 有效,其他浏览器无效

1
2
const el = document.getElementById('foo');
el.textContent = 'foo';

[译] JavaScript 技巧 —— 子代构造函数,文本选择,内联 Workers 等等
【译】JS代码整洁之道——快速最佳实践
JavaScript闭包应用介绍
如何精确统计页面停留时长

You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.