Home  >  Article  >  Web Front-end  >  14 Tips for Best JS Code Writing_javascript tips

14 Tips for Best JS Code Writing_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:12:25765browse

When writing any programming code, different developers will have different opinions. But it’s always good to refer to it, and here are 14 of the best JS coding tips from Javascript Toolbox.

1. Always use var
In JavaScript, variables are either global scope or function scope. Using the var keyword will be the key to keeping variables concise and clear. When declaring a variable that is either global or function-level, always prepend the var keyword. The following example will highlight the potential problems of not doing this.

Problems caused by not using Var

var i=0; // This is good - creates a global variable
function test() {
 for (i=0; i<10; i++) {
  alert("Hello World!");
 }
}
test();
alert(i); // The global variable i is now 10!

Because the variable i in the variable function does not use var to make it a function-level variable, in this example it refers to a global variable. It is a common practice to always use var to declare global variables, but it is crucial to use var to define a function-scoped variable. The following two methods are functionally equivalent:

Correct function

function test() {
var i=0;
for (i=0; i10; i++) {
alert("Hello World!");
}
}

Correct function

function test() {
for (var i=0; i10; i++) {
alert("Hello World!");
}
}

2. Feature detection instead of browser detection
Some code is written to discover the browser version and perform different actions based on the client the user is using. This, in general, is a very bad practice. A better approach is to use feature detection. Before using an advanced feature that older browsers may not support, first check whether (the browser) has this function or feature, and then use it. It's better to detect the browser version alone, even if you know its capabilities. You can find an in-depth article discussing this issue here.

Example:

if (document.getElementById) {
var element = document.getElementById('MyId');
}
else {
alert('Your browser lacks the capabilities required to run this script!');
}

3. Use square bracket notation

Use square bracket notation when access is determined at execution time or includes object properties that cannot be accessed using the . symbol. If you are not an experienced Javascript programmer, it is a good practice to always use square brackets.

The properties of an object are accessed in two fixed ways: . notation and [ ] square bracket notation:

.Notation

MyObject.property

 [ ] Square bracket notation

MyObject["property"]

Use . sign, the attribute name is hard code and cannot be changed during execution. Using [ ] square brackets, the property name is a string calculated from the property name. The string could be hard code, it could be a variable, or it could even be a function that calls back a string value. If an attribute name is generated during execution, square brackets are required if you have attributes like value1″, value2″, and value3″ and want to use the variable i=2 to access

This works:

MyObject["value" i]

This is not allowed:

MyObject.value i

And in some server-side environments (PHP, Struts, etc.), the Form form is appended with a [ ] number to indicate that the Form form must be treated as an array on the server side. In this case, using the . symbol to reference a field containing the symbol [ ] will not work, because [ ] is the syntax for referencing a Javascript array. Therefore, the [ ] notation is necessary: ​​

This works:

formref.elements["name[]"]

This is not allowed:

formref.elements.name[]

The recommended use of [ ] square bracket notation means that it is always used when it is (obviously) needed. When there is no strict need to use it, it is a matter of private preference and custom. A good rule of thumb is to use . notation to access standard object properties and [ ] square bracket notation to access page-defined object properties. Thus, document["getElementById"]() is a perfectly valid use of [ ] square bracket notation, but document.getElementById() is syntactically preferred because getElementById is a standard document object property defined in the DOM specification. Mixing these two notations makes it clear in code which are standard object properties and which property names are defined by the context:

document.forms["myformname"].elements["myinput"].value

Here, forms is a standard attribute of document, and the form name myformname is defined by the page. At the same time, the elements and value attributes are standard attributes defined by the specification. And myinput is defined by the page. The syntax of this page makes it very easy to understand (the content of the code). It is a recommended idiom to follow, but it is not a strict principle.

 4. Avoid eval

In Javascript, the eval() function is a method to execute arbitrary code during execution. In almost all cases, eval should not be used. If it's on your page, there's a better way to do what you do. As an example, eval is often used by programmers who don't know to use square bracket notation.

In principle, Eval is evil (Eval is the devil). Don't use it unless you are an experienced developer and know that your situation is an exception.

 5. Correctly reference forms and form elements

 All html forms should have a name attribute. For XHTML documents, the name attribute is not required, but the Form tag should have a corresponding id attribute and must be referenced using document.getElementById(). Using an index method like document.forms[0] to reference a form is a bad practice in almost all cases. Some browsers treat elements in the document named with form as an available form attribute. This is unreliable and should not be used.

The following example shows how to prevent incorrect reference to a form input using square brackets and the correct object reference method:

Correctly quote form input:

document.forms["formname"].elements["inputname"]

Bad approach:

document.formname.inputname

If you want to reference two form elements in a function, a better approach is to reference the form object first and store it in a variable. This avoids repeated queries to resolve references to the form:

Copy code The code is as follows:

var formElements = document.forms["mainForm"].elements;
formElements["input1"].value="a";
formElements["input2"].value="b";

When you use onChange or other similar event handling methods, a good practice is to always refer to the input element itself through a reference to the function. All input elements carry a reference to the containing Form:

Copy code The code is as follows:

input type="text" name="address" onChange="validate(this)"

function validate(input_obj) {
//Reference the form
that contains this element var theform = input_obj.form;
// Now you can reference the form itself without using hard code
if (theform.elements["city"].value=="") {
alert("Error");
}
}

To access form properties by referencing the form element, you can write a function that does not contain hard code to reference any form with a specific name on this page. This is a very good practice because the function becomes reusable.

6 Avoid with

The with statement in Javascript inserts an object at the front of a scope, so any property/variable references will be resolved against the object first. This is often used as a shortcut to avoid repeated references:

Example of using with:

Copy code The code is as follows:

with (document.forms["mainForm"].elements) {
input1.value = "junk";
input2.value = "junk";
}

But the problem is that the programmer has no way to verify that input1 or input2 has actually been treated as an attribute of the Form element array. It first checks for properties by those names, and if not found, it continues (down) the scope. Finally, it tries to treat input1 and input2 as one global object in the global object, which ends up with an error.

The workaround is: create a reference to reduce the referenced object, and use it to resolve these references.

Use a reference:

Copy code The code is as follows:

var elements = document.forms["mainForm"].elements;
elements.input1.value = "junk";
elements.input2.value = "junk";

7. Use onclick instead of javascript in anchors: Pseudo-Protocol

If you want to trigger Javascript code in a tag, choose onclick instead of JavaScript: pseudo-protocol; the Javascript code run using onclick must return true or false (or an expression than evalues ​​to true or false [This sentence needs to How to translate it? This is how I understand it: an expression with priority higher than true or false]) to return the tag itself: if true is returned, the anchor's href will be treated as a general link; if false is returned, The href will be ignored. This is why return false; is often included at the end of the code handled by onclick.

Correct syntax:

a href="javascript_required.html"go/a

In this example, the doSomething() function (defined in a corner of the page) will be called when clicked. The href will never be accessed by browsers with Javascript enabled. The document javascript_required.html will only be loaded in browsers where you can alert that Javascript is required but the user has not enabled it. Typically, when you ensure that the user will have Javascript support turned on, to keep things simple, the link will only contain href=#. This practice is not encouraged. It's usually a good idea to provide a local-returning page without javascript enabled.

Sometimes, many people want to access a link on a case-by-case basis. For example, when a user is leaving one of your form pages and wants to validate first to make sure nothing has been changed. In this case, your onclick will access a function that returns a query whether the link should be followed:

Conditional link access:

Copy code The code is as follows:

a href="/"Home/a

function validate() {
return prompt("Are you sure you want to exit this page?");
}

在这个实例中,validate() 函数必须只返回 ture 或 false。ture 的时候用户将被允许问题 home 页面,或 false 的时候链接不被访问。这个例子提示确认(其行为),以访问 ture 或 false,这完全由用户点击确实或者取消决定。

  下面是一些不应该的例子。如果你在自己的页面中看到下面这样的代码,这是不正确的,需要被修改:

  什么是不应该做的:

复制代码 代码如下:

a href="javascript:doSomething()"link/a
a href="#"link/a
a href="#"link/a
a href="#"link/a

8. 使用一元 + 号运算符使类型转向Number
  在Javascript中,+号运算符同时充当数学加号和连接符。这会在form表单的域值相加时出现问题,例如,因为Javascript是 一个弱类型语言,form 域的值将会被当作数组来处理,而你把它们+一起的时候,+将被当成连接符,而非数学加号。

  有问题的例子:

form name="myform" action="[url]"
input type="text" name="val1" value="1"
input type="text" name="val2" value="2"
/form

function total() {
var theform = document.forms["myform"];
var total = theform.elements["val1"].value + theform.elements["val2"].value;
alert(total); // 这个将会弹出 "12", 但你想要的是 3!
}


解决这个问题,Javascript 需要一个提示来让它把这些值当做数字来处理。你可以使用+号来把数组转换成数字。给变量或者表达式前置一个+号将会强制其当作一个数字来处理,而这也将使得数学+得以成功应用。

  修改好的代码:

function total() {
var theform = document.forms["myform"];
var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
alert(total); // This will alert 3
}

9. 避免 document.all
  document.all 是由Microsoft 的 IE 所引进的,并不是一个标准的 Javascript DOM 特性。尽管大多数新的浏览器支持它以支持依赖于它的糟糕代码,(而)还有很多浏览器是不支持的。

  并没有理由其他方法都不适用,而一个老的IE浏览器(5.0)需要支持,而在Javascript中使用 document.all 作为一个折衷方法。 你并不需要使用 document.all 来检测其是不是IE浏览器,因为其他浏览器现在一般都支持。

  只把 document.all 当做最后的选择:

if (document.getElementById) {
var obj = document.getElementById("myId");
}
else if (document.all) {
var obj = document.all("myId");
}

一些使用 document.all 的原则:

•同尝试其他方法
•当其作为最后的选择
•当需要支持 5.0 版本以下的 IE 浏览器
•总是使用 if (document.all) { } 来查看是否支持.
  10. 不要在脚本代码块中使用HTML注释
  在 Javascript 的旧日子(1995)里,诸如 Netscape 1.0 的一些浏览器并不支持或认识 script 标签。所以,当 Javascript 第一次被发布,需要有一个技术来让实些代码不被当做文本显示于旧版浏览器上。有一个hack 是在代码中使用 HTML 注释来隐藏这些代码。

  使 HTML 注释并不好:

script language="javascript"
!--
// code here
//--
/script

在今天,没有任何一个常用的浏览器会忽略掉 script 标签。因此,再没必要隐藏 Javascript 源代码。事实上,它还可以因为下面的理由,被认为是无益的:

•在 XHTML 文档中,源代码将向所有浏览器隐藏并被渲染成无用的(内容);
•– 在 HTML 注释并不允许 ,这个会让任何递减操作将失效。
  11. 避免乱用全局命名空间
  一般很少需要全部变量和函数。全局使用将可能导致 Javascript 源文件文档冲突,和代码中止。因此,一个好的做法是在一个全局命名空间内采用函数性的封装。有多个方法可以完成这个任务,有此相对比较复杂。最简单的方法 是创建一个全局对象,并把属性和方法指派给这个对象:

  创建一个命名空间:

var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }

MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7

命名空间也可以使用 Closures(闭包?) 来创建,并且 Private Member Variables (私有变量?) 也可以伪装于 Javascript中。

12. 避免同步的 ajax 调用

  当使用Ajax请求时,你要么选择异步模式,要么使用同步模式。当浏览器行为可以继续执行,异步模式将请求放在后台执行,同步模式则会等待请求完成后才继续。

  应该避免同步模式做出的请求。这些请求将会对用户禁用浏览器,直至请求返回。一旦服务器忙,并需要一段时间来完成请求,用户的浏览器(或者 OS)将不能做任何其他的事,直至请求超时。

  如果你觉得自己的情况需要同步模式,最大的可能是你需要时间来重新想一下你的设计。很少(如果有的话)实际上需要同步模式的 Ajax 请求。

13. 使用 JSON

  当需要将数据结构存储成纯文本,或者通过 Ajax 发送/取回数据结构,尽可能使用 JSON 代替 XML。JSON (JavaScript Object Notation) 是一个更简洁有效的数据存储格式,并且不依赖任何语言(and is a language-neutral)。

14. 使用正确的 script 标签

  不造成在 script 中的使用LANGUAGE 属性。一个合适的方式是创建如下的 Javascript 代码块:

<script type="text/javascript">
// code here
</script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn