Home  >  Article  >  Web Front-end  >  JavaScript-summarizing common code writing specifications

JavaScript-summarizing common code writing specifications

黄舟
黄舟Original
2017-02-22 13:21:231028browse

javascript Code Specifications

Code Specifications We should follow the ancient principle: "Just because you can do it doesn't mean you should do it."

Global namespace pollution

Always wrap the code in an immediate function expression to form an independent module.

Not recommended

var x = 10,
    y = 100;
console.log(window.x + ' ' + window.y);

Recommended

;(function(window){
    'use strict';
    var x = 10,
        y = 100;
    console.log(window.x + ' ' + window.y);
}(window));

Execute function immediately

Execute immediately in In the function , if the global variable is useful, it should be passed through the variable, so that can be executed immediately. When the function body of the function is called, it can be called in the form of a local variable, which can improve program performance to a certain extent. .

And you should add undefined to the formal parameters of the immediately executed function in the last position. This is because undefined can be read and written in ES3. If the value of undefined is changed in the global position , your code may not get overdue results.

It is also recommended to add semicolons at the beginning and end of Immediately execute the function to avoid affecting our own code due to irregularities in other people's code during merging

Not recommended

(function(){
    'use strict';
    var x = 10,
        y = 100,
        c,
        elem=$('body');
    console.log(window.x + ' ' + window.y);
    $(document).on('click',function(){

    });
    if(typeof c==='undefined'){
        //你的代码
    }
}());

Recommended

;(function($,window,document,undefined){
    'use strict';
    var x = 10,
        y = 100,
        c,
        elem=$('body');
    console.log(window.x + ' ' + window.y);
    $(document).on('click',function(){

    });
    if(typeof c==='undefined'){
        //你的代码
    }
}(jQuery,window,document));

Strict mode

ECMAScript 5 strict mode can be within the entire script or within a single method Activated. It will perform more stringent error checking corresponding to different javascript contexts. Strict mode also ensures that JavaScript code is more robust and runs faster.

Strict mode prevents the use of reserved keywords that are likely to be introduced in the future.

You should enable strict mode in your script, preferably in a standalone immediate function. Avoid using it in the first line of your script, which will cause strict mode to be enabled in all your scripts. This may cause problems with some third-party libraries.

Not recommended

'use strict';
(function(){

}());

Recommended

(function(){
    'use strict';
}());

Variable declaration

For all variable declarations, we Var should be specified. If var is not specified, an error will be reported in strict mode. Variables in the same scope should be declared with a var as much as possible, and multiple variables are separated by ",".

Not recommended

function myFun(){
    x=5;
    y=10;
}

Not completely recommended

function myFun(){
    var x=5;
    var y=10;
}

Recommended

function myFun(){
    var x=5,
        y=10;
}

Use comparison judgment with type judgment

Always use the === precise comparison operator to avoid the trouble caused by JavaScript's forced type conversion during the judgment process.

If you use the === operator, the comparison will only be valid if both parties are of the same type.

Not recommended

(function(w){
  'use strict';

  w.console.log('0' == 0); // true
  w.console.log('' == false); // true
  w.console.log('1' == true); // true
  w.console.log(null == undefined); // true

  var x = {
    valueOf: function() {
      return 'X';
    }
  };

  w.console.log(x == 'X');//true

}(window.console.log));

Recommended

(function(w){
  'use strict';

  w.console.log('0' === 0); // false
  w.console.log('' === false); // false
  w.console.log('1' === true); // false
  w.console.log(null === undefined); // false

  var x = {
    valueOf: function() {
      return 'X';
    }
  };

  w.console.log(x === 'X');//false

}(window));

Logical operations when assigning values ​​to variables

Logical operators || and && can also be used to return Boolean values. If the operand is a non-Boolean object, each expression will be evaluated from left to right. Based on this operation, eventually an expression is always returned. This can be used to simplify your code when assigning values ​​to variables.

Not recommended

if(!x) {
  if(!y) {
    x = 1;
  } else {
    x = y;
  }
}

Recommended

x = x || y || 1;

Semicolon

Always use a semicolon because Implicit code nesting can cause subtle problems. Of course, we must fundamentally eliminate these problems [1]. The following examples illustrate the dangers of missing semicolons:

// 1.
MyClass.prototype.myMethod = function() {
  return 42;
}  //这里没有分号

(function() {

})();

 //2.
var x = {
  'i': 1,
  'j': 2
}  // 这里没有分号
//我知道这样的代码你可能永远不会写,但是还是举一个例子
[ffVersion, ieVersion][isIE]();

 // 3.
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese]  // 这里没有分号

-1 == resultOfOperation() || die();

Error result

  1. JavaScript error - the function that first returned 42 was In the second function, the parameters are passed into the call, and then the number 42 is also "called", causing an error.

  2. 80% of the time you will get the error message 'no such property in undefined', because the call in the real environment looks like this: xffVersion, ieVersion().

  3. die is always called. Because the result of subtracting an array by 1 is NaN, it is not equal to anything (regardless of whether resultOfOperation returns NaN). So the final result is that the value obtained after die() is executed will be assigned to THINGS_TO_EAT.

Function declaration within the statement block

Do not declare functions within the statement block , which is illegal in ECMAScript 5's strict mode. Function declarations should be at the top level of the scope. However, within the statement block, the function declaration can be converted into a function expression and assigned to a variable.

Not recommended

if (x) {
  function foo() {}
}

Recommended

if (x) {
  var foo = function() {};
}

Do not use the eval function

eval() is not only confusing The context is still dangerous, there is always a better, clearer, safer way to write your code, so try not to use the eval function.

Array and object literals

1. Use array and object literals to replace array and object constructors. The array constructor makes it easy to make mistakes with its arguments.

Not recommended

//数组长度3
var a1 = new Array(x1, x2, x3);
//数组长度2
var a2 = new Array(x1, x2);

//如果x1是一个自然数,那么它的长度将为x1
//如果x1不是一个自然数,那么它的长度将为1
var a3 = new Array(x1);

var a4 = new Array();

Because of this, if the code parameter is changed from two to one, the length of the array is likely to change unexpectedly. To avoid weird situations like this, always use readable array literals.

recommend

var a = [x1, x2, x3];
var a2 = [x1, x2];
var a3 = [x1];
var a4 = [];

2.对象构造器不会有类似的问题,但是为了可读性和统一性,我们应该使用对象字面量。

不推荐

var o = new Object();

var o2 = new Object();
o2.a = 0;
o2.b = 1;
o2.c = 2;
o2['strange key'] = 3;

推荐

var o = {};
var o2 = {
  a: 0,
  b: 1,
  c: 2,
  'strange key': 3
};

三元条件判断(if 的快捷方法)

用三元操作符分配或返回语句。在比较简单的情况下使用,避免在复杂的情况下使用。没人愿意用 10 行三元操作符把自己的脑子绕晕。

不推荐

if(x === 10) {
  return 'valid';
} else {
  return 'invalid';
}

推荐

return x === 10 ? 'valid' : 'invalid';

for循环

使用for循环过程中,数组的长度,使用一个变量来接收,这样有利于代码执行效率得到提高,而不是每走一次循环,都得重新计算数组长度

不推荐

for(var i=0;i<arr.length,i++){

}

推荐

for(var i=0,len=arr.length;i<len,i++){

}

重复的dom操作

重复的dom操作,使用一个变量来进行接收很有必要,而不是频繁的去操作dom树,这对性能与代码的整洁及易维护性带来不好的影响

不推荐

$(&#39;.myp&#39;).find(&#39;.span1&#39;).text(&#39;1&#39;);
$(&#39;.myp&#39;).find(&#39;.span2&#39;).text(&#39;2&#39;);
$(&#39;.myp&#39;).find(&#39;.span3&#39;).text(&#39;3&#39;);
$(&#39;.myp&#39;).find(&#39;.span4&#39;).text(&#39;4&#39;);

推荐

var myp=$(&#39;.myp&#39;);
myp.find(&#39;.span1&#39;).text(&#39;1&#39;);
myp.find(&#39;.span2&#39;).text(&#39;2&#39;);
myp.find(&#39;.span3&#39;).text(&#39;3&#39;);
myp.find(&#39;.span4&#39;).text(&#39;4&#39;);

在jquery .end()可使用的情况下应该优先使用.end()

推荐

$(&#39;.myp&#39;).find(&#39;.span1&#39;).text(&#39;1&#39;)
           .end().find(&#39;.span2&#39;).text(&#39;2&#39;);
           .end().find(&#39;.span3&#39;).text(&#39;3&#39;);
           .end().find(&#39;.span4&#39;).text(&#39;4&#39;);

注释规范

在描写注释时,推荐格式化且统一的注释风格,在写注释时尽量描述写代码时的思路,而不是代码做了什么。

不推荐

//获取订单
function getOrderByID(id){
    var order;
    //...
    return order;
}

方法的注释应该统一用块级注释

推荐

/**
 * 根据订单id获取订单详细数据
 * @param  {[number]} id [订单ID]
 * @return {[order]}    [订单详细信息]
 */
function getOrderByID(id){
    var order;
    //...
    return order;
}

以上就是JavaScript-总结常用代码书写规范的内容,更多相关内容请关注PHP中文网(www.php.cn)!



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