1. 变量提升(Hoisting)陷阱
console.log(foo); // undefined
var foo = 'bar';
// 编译后实际执行顺序:
var foo;
console.log(foo);
foo = 'bar';
解析:var声明的变量会提升到作用域顶部,但赋值不提升。推荐使用let/const避免此类问题。
2. 隐式类型转换迷思
console.log(1 + '1'); // "11"
console.log('5' - 2); // 3
console.log([] == false) // true
解析:==运算符会进行隐式类型转换,建议使用===严格比较符避免意外结果。
3. this指向混乱场景
const obj = {
name: 'test',
print: function() {
setTimeout(function() {
console.log(this.name); // undefined
}, 100)
}
}
解决方案:使用箭头函数或bind绑定上下文:
setTimeout(() => {
console.log(this.name); // 'test'
}, 100)
4. 异步回调地狱
// 金字塔式回调
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
// 无限嵌套...
})
})
})
解决方案:使用Promise链式调用或async/await:
async function loadData() {
const a = await getData()
const b = await getMoreData(a)
return await getMoreData(b)
}
5. 闭包内存泄漏
function createClosure() {
const bigData = new Array(1000000).fill('*')
return function() {
console.log('闭包保留了bigData引用!')
}
}
解析:闭包会保留外部变量引用,需注意及时解除不需要的引用。
结语
掌握这些常见误区不仅能避免代码bug,更能提升对JavaScript运行机制的理解。建议结合ES6+新特性编写更安全可靠的代码,善用Lint工具检测潜在问题,让JavaScript真正成为你的得力助手而非噩梦来源!

被折叠的 条评论
为什么被折叠?



