In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the common BUG and repair methods of JavaScript in the front end of Web. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.
JavaScript seems to be a very simple language, but it is not. It has a lot of details that are easy to get wrong, which can lead to BUG if you don't pay attention to it.
I. erroneous reference to this
It is easy to get the scope of the this keyword wrong in closures or callbacks. For example:
Game.prototype.restart = function () {
This.clearLocalStorage ()
This.timer = setTimeout (function () {
This.clearBoard (); / / what does this mean here?
}, 0)
}
If we execute the above code, we will see an error:
Uncaught TypeError: undefined is not a function
The reason for the error is that when you call the setTimeout function, you actually call window.setTimeout (). The anonymous function passed in setTimeout is in the context of window, so this points to window, but window does not have a clearBoard method.
How to solve the problem? Define a new variable reference to the this that points to the Game object, and then you can use it.
Game.prototype.restart = function () {
This.clearLocalStorage ()
Var self = this; / / bind the object that this points to to self
This.timer = setTimeout (function () {
Self.clearBoard ()
}, 0)
}
Or use the bind () function:
Game.prototype.restart = function () {
This.clearLocalStorage ()
This.timer = setTimeout (this.reset.bind (this), 0); / / bind to 'this'
}
Game.prototype.reset = function () {
This.clearBoard (); / / the reference to this here is correct
}
2. BUG related to block scope
In most programming languages, each function block has a separate new scope, but not in JavaScript. For example:
For (var I = 0; I
< 10; i++) { /* ... */ } console.log(i); // 会输出什么呢? 通常在这种情况下,调用console.log()会输出undefined或则报错。不过呢,这里会输出10。在JavaScript中,即使for循环已经结束,变量i依然存在,并且记录最后的值。有些开发者会忘记这一点,然后导致许多bug。我们可以使用let而不是for来杜绝这一问题。 三、内存泄漏 你需要监控内存使用量,因为泄露很难避免。内存泄露可能由于引用不存在的对象或则循环引用导致。 · 如何避免:关注对象的可访问性(reachability)。 · 可访问的对象: § 现有的call stack任何位置可以访问的对象 § 全局对象 当一个对象可以通过引用访问到,那么会在内存中保存。浏览器的垃圾回收器仅仅会把那些不可访问的对象回收。 四、混淆的相等判断 JavaScript自动将所有在布尔环境下的变量类型转换为布尔类型,但是可能导致bug。举例: // 所有都是true console.log(false == '0'); console.log(null == undefined); console.log(" \t\r\n" == 0); console.log('' == 0); // 注意:下面两个也是 if ({}) // … if ([]) // … {}和[]都是对象,他们都会被转换为true。为了防止bug出现,推荐使用===和!==来做比较,因为不会隐式做类型转换。 五、低效的DOM操作 在JavaScript中,你可以轻松操作DOM(添加、修改和删除),但是开发者往往很低效地去操作。这会导致bug出现,因为这些操作非常耗费计算资源。为了解决这个问题,推荐使用文档碎片(Document Fragment),如果你需要操作多个DOM元素。 六、在for循环中错误的定义函数 举例: var elements = document.getElementsByTagName('input'); var n = elements.length; // 假设我们有10个元素 for (var i = 0; i < n; i++) { elements[i].onclick = function() { console.log("元素编号#" + i); }; } 如果我们有10个元素,那么点击任何一个元素都会显示"元素编号#10"!因为在onclick被调用的时候,for循环已经结束,因此所有的i都是10。 解法: var elements = document.getElementsByTagName('input'); var n = elements.length; // 假设有10个元素 var makeHandler = function(num) { // outer function return function() { // inner function console.log("元素编号##" + num); }; }; for (var i = 0; i < n; i++) { elements[i].onclick = makeHandler(i+1); } makeHandler在for循环执行的时候立即被调用,获取到当前的值i+1,并且存储在变量num中。makeHandler返回一个函数使用num变量,该函数被绑定到元素的点击事件。 七、通过原型错误地继承 开发者如果没能正确理解继承的原理,那么就可能写出有bug的代码: BaseObject = function(name) { if(typeof name !== "undefined") { this.name = name; } else { this.name = 'default' } }; var firstObj = new BaseObject(); var secondObj = new BaseObject('unique'); console.log(firstObj.name); // ->Output 'default'
Console.log (secondObj.name); / /-> output 'unique'
However, if we do the following:
Delete secondObj.name
So:
Console.log (secondObj.name); / /-> output 'undefined'
What we actually want is to print the default name.
BaseObject = function (name) {
If (typeof name! = = "undefined") {
This.name = name
}
}
BaseObject.prototype.name = 'default'
Each BaseObject inherits the name property, and the default value is default. At this point, if the name attribute of secondObj is deleted, the search through the prototype chain will return the correct default value.
Var thirdObj = new BaseObject ('unique')
Console.log (thirdObj.name); / /-> output 'unique'
Delete thirdObj.name
Console.log (thirdObj.name); / /-> output 'default'
Invalid references in the instance method
Let's implement a simple constructor to create an object:
Var MyObject = function () {}
MyObject.prototype.whoAmI = function () {
Console.log (this = window? "window": "MyObj")
}
Var obj = new MyObject ()
For ease of use, we define the variable whoAmI to reference obj.whoAmI:
Var whoAmI = obj.whoAmI
Print it out and see:
Console.log (whoAmI)
The console outputs:
Function () {
Console.log (this = window? "window": "MyObj")
}
Now let's compare the difference between the two calls:
Obj.whoAmI (); / / output "MyObj" (as expected)
WhoAmI (); / / output "window" (unexpectedly output window)
When we assign obj.whoAmI to whoAmI, the new variable whoAmI is defined globally, so this points to the global window, not MyObj. If we really want to get a reference to the function of MyObj, we need to be in its scope.
Var MyObject = function () {}
MyObject.prototype.whoAmI = function () {
Console.log (this = window? "window": "MyObj")
}
Var obj = new MyObject ()
Obj.w = obj.whoAmI; / / still in the scope of obj Ningbo Men's Hospital http://www.jzspfk.com/
Obj.whoAmI (); / / output "MyObj"
Obj.w (); / / output "MyObj"
9. Misuse of string in the first argument of settimeout/setlnterval function
If you take a string as setTimeout/setTimeInterval, it will be passed to the function constructor and a new function will be built. This operation is slow and inefficient and leads to the emergence of bug.
Var hello = function () {
Console.log ("hello, fundebug!")
}
SetTimeout ("hello", 1000)
A good alternative is to pass in a function as an argument:
SetInterval (logTime, 1000); / / pass in the logTime function
SetTimeout (function ()) {/ / pass in an anonymous function
LogMessage (msgValue)
}, 1000)
Failed to use strict mode successfully
Using strict model will add a lot of restrictions to enhance security and prevent some errors. If you don't use strict mode, you will be missing a good assistant to help you avoid mistakes:
Easier to debug
Avoid accidentally defining global variables that should not be defined
Avoid this implicit conversion
Avoid repeated use of attribute names or parameter values
Eval () is more secure
Invalid use of delete will automatically throw an error
About the Web front-end JavaScript common BUG and repair methods are shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.