文档详情

超实用的JavaScript技巧及最佳实践(上).doc

发布:2018-05-20约6.73千字共5页下载文档
文本预览下载声明
众所周知,JavaScript是一门非常流行的编程语言,开发者用它不仅可以开发出炫丽的Web程序,还可以用它来开发一些移动应用程序(如PhoneGap或Appcelerator),它还有一些服务端实现,比如NodeJS、Wakanda以及其它实现。此外,许多开发者都会把JavaScript选为入门语言,使用它来做一些弹出窗口等小东西。   在这篇文章中,作者将会向大家分享JavaScript开发的小技巧、最佳实践等非常实用的内容,不管你是前端开发者还是服务端开发者,都应该来看看这些小技巧,它们绝对会让你受益的。   文中所提供的代码片段都已经过最新版的Chrome 30测试,该浏览器使用V8 JavaScript引擎(V8 5)。   1.第一次给变量赋值时,别忘记var关键字   给一个未声明的变量赋值,该变量会被自动创建为全局变量,在JS开发中,应该避免使用全局变量。   2.使用===替换==   并且永远不要使用=或!=。 1 2 3 4 5 6 7 8 [10] === 10??? // is false [10]? == 10??? // is true 10 == 10???? // is true 10 === 10??? // is false ?[]?? == 0???? // is true ?[] ===? 0???? // is false ? == false?? // is true but true == a is false ? ===?? false // is false   3.使用分号来作为行终止字符   在行终止的地方使用分号是一个很好的习惯,即使开发人员忘记加分号,编译器也不会有任何提示,因为在大多数情况下,JavaScript解析器会自动加上。   4.创建构造函数 1 2 3 4 5 6 function Person(firstName, span id=5_nwp style=width: auto; height: auto; float: none;a id=5_nwl href=/html/html5/ target=_blank mpid=5 style=text-decoration: none;span style=color:#0000ff;font-size:14px;width:auto;height:auto;float:none;last/span/a/spanName){ ????tspan id=6_nwp style=width: auto; height: auto; float: none;a id=6_nwl href=/cpro/ui/uijs.php?adclass=0app_id=0c=newscf=1001ch=0di=128fv=20is_app=0jk=b386f22a89fceda6k=hisk0=hiskdi0=0luki=2mcpm=0n=10p=baiduqcprrb=0rs=1seller_id=1sid=a6edfc892af286b3ssp2=1stid=9t=tpclicked3_hctd=1922429tu=u1922429u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3589%2Ehtmlurlid=0 target=_blank mpid=6 style=text-decoration: none;span style=color:#0000ff;font-size:14px;width:auto;height:auto;float:none;his/span/a/span.firstName =? firstName; ????this.lastName = lastName;??????? }? ? var Saad = new Person(Saad, Mousliki);   5.应当小心使用typeof、instanceof和constructor 1 2 3 4 var arr = [a, b, c]; typeof arr;?? // return object arr? instanceof Array // true arr.constructor();? //[]   6.创建一个Self-calling函数   这通常会被称为自我调用的匿名函数或立即调用函数表达式(LLFE)。当函数被创建的时候就会自动执行,好比下面这个: 1 2 3 4 5 6 7 (function(){ ????// some private code that will be executed automatically }
显示全部
相似文档