search
HomeWeb Front-endJS TutorialJavascript coding conventions (coding specifications)

Javascript coding conventions (coding specifications)

May 31, 2018 am 10:31 AM
javascriptjsspecification

这篇文章主要介绍了Javascript 编码约定(编码规范),需要的朋友可以参考下

1、使用 strict 模式

在一个作用域(包括函数作用域、全局作用域)中,可以使用

"use strict";

来开启 strict 模式。

2、缩进

用 Tab 键进行代码缩进,以节约代码大小,使用4个空格的宽度来进行缩进(JSLint 建议)。

3、符号

1) 大括号

与语句放同一行,放于最后面;仅有一行语句,也使用大括号:

if (true) {
  //true
} else {
  //false
}

while (true) {
  //alert(1);
}

2) 空格

在逗号、分号、冒号后加空格
在操作符前后加空格
在大括号开始符之前
在大括号结束符和 else、while 或 catch 之间
在 for 的各个部分
如:

var a = [1, 2, 3];
var obj = {
  name: 'name',
  value: 'value'
};
for (var i = 0; i < 10; i++) {}
function func(a, b, c) {}

c = a + b;
if (a && b || c) {
  //if
} else {
  //else
}

try {
  //try
} catch(err) {
  //catch
}

3) 所有语句结束后,使用 ; 号结束

4、命名

对象:使用驼峰式,如:MyClass
方法、变量:使用混合式,如:getName(), myName
常量:大写加下划线,如:MY_NAME

5、单一 var 模式

只使用一个 var 在函数顶部进行变量声明,作用如下:

1) 提供一个单一的地址已查找到函数需要的所有局部变量
2) 防止出现变量在定义前就被使用的逻辑错误
3) 帮助牢记要声明变量,尽可能少地使用全局变量
4) 更少的编码

function func() {
  var a = 1,
    b = 2, 
    sum = a + b,
    obj = {
      name: &#39;name&#39;,
      value: &#39;value&#39;
    },
  $btn = $(&#39;#btn&#39;);
  //函数体
}

6、循环

1) for 循环

var i, arr = [];
for (i = arr.length; i--;) {
  //arr[i];
}

注:

for (var i = 0; i < document.getElementsByName().length; i++) {
  //document.getElementsByName()[0];
}

这种方式每次对 i 进行长度比较的使用对会进行 document 的查询,而通常 DOM 操作是非常耗时的。

2) while 循环

var arr = [], 
  i = arr.length;
while (i--) {
  //处理
}

3) for-in 循环

var i,
  hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
  if (hasOwn.call(man, i)) { //过滤
    console.log(i, &#39;:&#39;, man[i]);
  }
}

7、switch 选择

switch (num) {
case 0:
  //do something
  break;
case 1:
  //do something
  break;
...
default:
  //do default
}

建议使用:

var obj = {
  &#39;0&#39;: function() {
    //do somethins
  },
  &#39;1&#39;: function() {
    // do somethis
  }, ...
}
if (obj.hasOwnProperty(num)) {
  obj[num]();
} else {
  //do default
}

8、使用 parseInt() 的数值约定

1) 每次都具体指定进制参数:

var month = &#39;09&#39;, day = &#39;08&#39;;
month = parseInt(month, 10); //不加进制参数便会转换为八进制
day = parseInt(day, 10);

2) 其他常用的将字符串转换为数值的方法:

+&#39;08&#39;;
Number(&#39;08&#39;);

9、字面量模式

不建议使用构造函数来定义:

// built in constructors (avoid)
var o = new Object();
var a = new Array();
var re = new RegExp(&#39;[a-z]&#39;, &#39;g&#39;);
var s = new String();
var n = new Number();
var b = new Boolean();
throw new Error(&#39;message&#39;);

建议使用更优的字面量模式:

// literals and primitives (prefer)
var o = {};
var a = [];
var re = /[a-z]/g;
var s = &#39;&#39;;
var n = 0;
var b = false;
throw {
  name: &#39;Error&#39;,
  message: &#39;message&#39;
}

10、其他

1) 变量内的简写单词如果在开头则全小写:xmlDocument,如果不在开头则全大写:loadXML
2) 变量必须是有意义的英文,禁止拼音

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Angular 4.x+Ionic3踩坑之Ionic3.x pop反向传值详解

基于vue中css预加载使用sass的配置方式详解

微信小程序中实现手指缩放图片的示例代码

The above is the detailed content of Javascript coding conventions (coding specifications). For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)