day*_*oli 5 javascript methods conditional-statements
在Learning Javascript - A Hands-On Guide to the Fundamentals of Modern Javascript 中的Working with the Attribute Node一章中,作者 Tim Wright 在第 73 页说:
删除一个属性就像获取一个属性一样简单。我们只是定位元素节点并使用该方法
removeAttribute()将其从那里取出。如果您尝试删除不存在的属性,则不会抛出 Javascript 异常,但最好使用hasAttribute()我们之前提到的相同方法,如代码清单 4.6.4 所示
清单 4.6.4 用于删除我们图像的类值的 Javascript
if(document.getElementById("pic").hasAttribute("class")) {
document.getElementById("pic").removeAttribute("class");
}
Run Code Online (Sandbox Code Playgroud)
如果没有任何异常抛出,是否不检查它是否存在或是否多余?会出现同样的结果。这本书说的论点是,在删除它之前检查参数可以节省浏览器通过不必要的代码解析,但if(document.getElementById("pic").hasAttribute("class")) {}甚至比单独解析还要长document.getElementById("pic").removeAttribute("class");!
为什么这是最佳实践呢?