Javascript coding conventions (coding specifications)
这篇文章主要介绍了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: 'name',
value: 'value'
},
$btn = $('#btn');
//函数体
}
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, ':', man[i]);
}
}
7、switch 选择
switch (num) {
case 0:
//do something
break;
case 1:
//do something
break;
...
default:
//do default
}
建议使用:
var obj = {
'0': function() {
//do somethins
},
'1': function() {
// do somethis
}, ...
}
if (obj.hasOwnProperty(num)) {
obj[num]();
} else {
//do default
}
8、使用 parseInt() 的数值约定
1) 每次都具体指定进制参数:
var month = '09', day = '08'; month = parseInt(month, 10); //不加进制参数便会转换为八进制 day = parseInt(day, 10);
2) 其他常用的将字符串转换为数值的方法:
+'08'; Number('08');
9、字面量模式
不建议使用构造函数来定义:
// built in constructors (avoid) var o = new Object(); var a = new Array(); var re = new RegExp('[a-z]', 'g'); var s = new String(); var n = new Number(); var b = new Boolean(); throw new Error('message');
建议使用更优的字面量模式:
// literals and primitives (prefer)
var o = {};
var a = [];
var re = /[a-z]/g;
var s = '';
var n = 0;
var b = false;
throw {
name: 'Error',
message: 'message'
}
10、其他
1) 变量内的简写单词如果在开头则全小写:xmlDocument,如果不在开头则全大写:loadXML
2) 变量必须是有意义的英文,禁止拼音
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
Angular 4.x+Ionic3踩坑之Ionic3.x pop反向传值详解
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!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe 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 DetailsApr 17, 2025 am 12:05 AMUnderstanding 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 UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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 WorksApr 14, 2025 am 12:05 AMThe 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 ImplementationsApr 13, 2025 am 12:05 AMDifferent 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 WorldApr 12, 2025 am 12:06 AMJavaScript'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)Apr 11, 2025 am 08:23 AMI 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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

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
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)






