源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JavaScript中日常收集常见的10种错误(推荐)

  • 时间:2021-04-05 00:55 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JavaScript中日常收集常见的10种错误(推荐)
[b] 1 对于this关键词的不正确使用[/b]
Game.prototype.restart = function () { 
this.clearLocalStorage(); 
this.timer = setTimeout (function() { 
this.clearBoard(); 
}, 0); 
};
运行上面的代码将会出现如下错误:
uncaught typeError:undefined is not a function
为什么会有这个错? this是指代当前对象本身,this的调用和它所在的环境密切相关。上面的错误是因为在调用setTimeout函数的时候,实际调用的是window.setTimeout,而在window中并没有clearBoard();这个方法; [b]下面提供两种解决的方法。[/b] 1,将当前对象存储在一个变量中,这样可以在不同的环境被继承。
Game.prototype.restart = function() { 
this.clearLocalStorage(); 
var self = this; 
this.timer = setTimeout(function(){ 
self.clearBoard(); }, 0); 
}; //改变了作用的对象 
2,使用bind()方法, 不过这个相比上一种会复杂,bind方法官方解释: msdn.microsoft.com/zh-cn/library/ff841995
Game.prototype.restart = function () { 
this.clearLocalStorage(); 
this.timer = setTimeout(this.reset.bind(this)), 
}; 
Game.prototype.reset = function() { 
this.clearBoard(); 
};
2 传统编程语言的生命周期误区 在js中变量的生存周期与其他语言不同,举个例子
for (var i=0; i<10;i++){ 
/* */ 
} 
console.log(i); //并不会提示 未定义,结果是10 
在js中这种现象叫:[code]variable hoisting[/code](声明提前) 可以使用let关键字。 3 内存泄漏 在js中无法避免会有内存泄漏,内存泄漏:占用的内存,但是没有用也不能及时回收的内存。 例如以下函数:
var theThing = null; 
var replaceThing = function() { 
var priorThing = theThing; 
var unused = function() { 
if (priorThing) { 
console.log(‘hi'); 
}; 
}; 
theThing = { 
longStr: new Array(1000000).join(‘*'), 
someMethod: function () { 
console.log(someMessage); 
} 
} 
setInterval(replaceThing, 1000);
如果执行这段代码,会造成大量的内存泄漏,光靠garbage collector是无法完成回收的,代码中有个创建数组对象的方法在一个闭包里,这个闭包对象又在另一个闭包中引用,,在js语法中规定,在闭包中引用闭包外部变量,闭包结束时对此对象无法回收。 4 比较运算符
console.log(false == ‘0'); // true 
console.log(null == undefinded); //true 
console.log(” \t\r\n” == 0);
以上所述是小编给大家介绍的JavaScript中日常收集常见的10种错误(推荐),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部