1.慎用全局变量
let i, str
for (i; i < 1000; i++) {
str += i
}
for (let i; i < 1000; i++) {
let str;
str += i
}
2.将使用中无法避免的全局变量缓存到局部
let a1 = document.getElementsByClassName('p1')
let a2 = document.getElementsByClassName('p2')
let a3 = document.getElementsByClassName('p3')
let a4 = document.getElementsByClassName('p4')
let a5 = document.getElementsByClassName('p5')
const doc = document
let a1 = doc.getElementsByClassName('p1')
let a2 = doc.getElementsByClassName('p2')
let a3 = doc.getElementsByClassName('p3')
let a4 = doc.getElementsByClassName('p4')
let a5 = doc.getElementsByClassName('p5')
3.通过原型对象添加附加方法
function person() {
this.fun = function () {
console.log("我是person的方法")
}
}
function person() {
}
person.prototype.fun = function () {
console.log("我是person的方法")
}
4.避开闭包陷阱
function foo() {
let ele = document.getElementById('btn')
ele.onclick = function () {
console.log(ele.id)
}
}
foo()
我们执行完foo函数之后,内部的ele还会继续引用着不会得到立刻的释放,所以会存在内存泄漏
function foo() {
let ele = document.getElementById('btn')
ele.onclick = function () {
console.log(ele.id)
}
ele = null;
}
foo()
我们执行完foo函数之后,内部的ele还会继续引用着不会得到立刻的释放,所以会存在内存泄漏
5.for循环优化
let arr = [2, 3, 4, 2, 1, 3, 4, 23]
for (let i; i < arr.length; i++) {
}
for (let i, len = arr.length; i < len; i++) {
}
6.循环最优化选择
let arr = [2, 3, 4, 2, 1, 3, 4, 23]
arr.forEach(item => {
})
for (let i = arr.length; i; i--) {
}
for(let i in arr){
}
7.文档碎片优化节点添加(减少操作dom)
for (let i = arr.length; i; i--) {
var p = document.createElement('p')
p.innerHTML = i
document.body.append(p)
}
const dd = document.createDocumentFragment()
for (let i = arr.length; i; i--) {
var p = document.createElement('p')
p.innerHTML = i
dd.append(p)
}
document.body.appendChild(dd)
8 定义对象的方式
const arr = []
arr[0] = 1
arr[1] = 2
arr[2] = 3
const arr = [1,2,3]