Properties
 
 • 当访问属性的时候,我们使用点(.)操作符。
var luke = {
jedi: true,
age: 28
}; // bad
var isJedi = luke['jedi']; // good
var isJedi = luke.jedi;

• 当以变量的方式访问属性的时候,用下标符号([])。——除非特殊需求,否则尽量避免使用obj[variable]的方式进行属性访问。

var luke = {
jedi: true,
age: 28
}; function getProp(prop) {
return luke[prop];
} var isJedi = getProp('jedi');
Variables
 
 • 总是使用var定义变量,否则会导致产生隐含全局变量。我们要尽量避免污染全局变量命名空间。
// bad
superPower = new SuperPower(); // good
var superPower = new SuperPower();

汤姆大叔—javascript系列文章中提到“JavaScript有隐含的全局概念,意味着你不声明的任何变量都会成为一个全局对象属性。在技术上,隐式全局变量并不是真正的全局变量,但它们是全局对象的属性。属性是可以通过delete操作符删除的,而变量是不能的。"

 • 使用一个var定义多个变量,每个变量在一个新行上。
// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z'; // good
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';

• 用var定义多个变量的时候,把不进行赋值的变量放置到最后——这是相当有益的。尤其是当你的变量需要前面变量值的时候。

// bad
var i, len, dragonball,
items = getItems(),
goSportsTeam = true; // bad
var i, items = getItems(),
dragonball,
goSportsTeam = true,
len; // good
var items = getItems(),
goSportsTeam = true,
dragonball,
length,
i;

• 把你的赋值变量放置在当前作用域的顶端。这将避免变量声明和hoisting(悬置/置顶解析/预解析)的问题。

// bad
function() {
test();
console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') {
return false;
} return name;
} // good
function() {
var name = getName(); test();
console.log('doing stuff..'); //..other stuff.. if (name === 'test') {
return false;
} return name;
} // bad
function() {
var name = getName(); if (!arguments.length) {
return false;
} return true;
} // good
function() {
if (!arguments.length) {
return false;
} var name = getName(); return true;
}
Hoisting
 
汤姆大叔:
  1、JavaScript中,你可以在函数的任何位置声明多个var语句,并且它们就好像是在函数顶部声明一样发挥作用,这种行为称为 hoisting(悬置/置顶解析/预解析)。
  2、对于JavaScript,只 要你的变量是在同一个作用域中(同一函数),它都被当做是声明的,即使是它在var声明前使用的时候。
 •  变量声明提升到当前作用域的顶端,而它们的赋值操作不一定要这么做。
function example() {
console.log(notDefined); // => throws a ReferenceError
} function example() {
console.log(declaredButNotAssigned); // => undefined
var declaredButNotAssigned = true;
} function example() {
var declaredButNotAssigned;
console.log(declaredButNotAssigned); // => undefined
declaredButNotAssigned = true;
}

•  匿名表达式会自动提升它们的变量名称(也就是说在var anonymous上面,example函数就已经知道有这个变量了),但是它们的函数体不会。

function example() {
console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function() {
console.log('anonymous function expression');
};
}

•  命名函数表达式也会提升它们的变量名称,而它们的函数名称和函数体不会这样做。

function example() {
console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() {
console.log('Flying');
}; function example() {
console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() {
console.log('named');
};
}
}

•  注意:函数声明会提升它们的变量名称还有它们的函数体

function example() {
superPower(); // => Flying function superPower() {
console.log('Flying');
}
}
Conditional Expressions & Equality
 
 •  使用 === 和 !== 代替==和!=。
== 和 != 会进行隐式类型转换,所以建议使用===和!==。
 •  强制使用对象的特性(ToBoolean)得到条件表达式的值,大致遵循以下简单规则。
  ◊ Objects 得到的值是true。
  ◊ Undefined得到的值是false。
  ◊ Null得到的值是false。
  ◊ Booleans得到的值是Boolean值(呵呵,当然)。
  ◊ Numbers 得到的值是:如果是+0,-0,或者NaN就是false,否则就是true。
  ◊ Strings 得到的值是:如果是'',就是false,否则就是true。
if ([0]) {
// true
// An array is an object, objects evaluate to true
}

•  使用快捷方式。

// bad
if (name !== '') {
// ...stuff...
} // good
if (name) {
// ...stuff...
} // bad
if (collection.length > 0) {
// ...stuff...
} // good
if (collection.length) {
// ...stuff...
}
Blocks
 
• 有{}的代码,我们换行处理。
// bad
if (test)
return false; // good
if (test) return false; // good
if (test) {
return false;
} // bad
function() { return false; } // good
function() {
return false;
}
Comments
 
• 对于多行注释使用/**  ... */。包含描述信息、参数类型和返回值。
 
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param <String> tag
// @return <Element> element
function make(tag) { // ...stuff... return element;
} // good
/**
* make() returns a new element
* based on the passed in tag name
*
* @param <String> tag
* @return <Element> element
*/
function make(tag) { // ...stuff... return element;
}
• 对于单行注释使用//。单行注释单独放置在一个新行上。在注释前面放置一个空行。
// bad
var active = true; // is current tab // good
// is current tab
var active = true; // bad
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this._type || 'no type'; return type;
} // good
function getType() {
console.log('fetching type...'); // set the default type to 'no type'
var type = this._type || 'no type'; return type;
}

• 对于一些问题,注释前加FIXME或TODO,这样将快速帮助开发者快速明白代码意图。

• 使用 // FIXME: 注释问题

function Calculator() {

  // FIXME: shouldn't use a global here
total = 0; return this;
}

• 使用 // TODO: 注释问题的解决方案

function Calculator() {

  // TODO: total should be configurable by an options param
this.total = 0; return this;
}
Type Casting & Coercion
 
• 在声明之前执行强制类型转换。
• 字符串
//  => this.reviewScore = 9;

// bad
var totalScore = this.reviewScore + ''; // good
var totalScore = '' + this.reviewScore; // bad
var totalScore = '' + this.reviewScore + ' total score'; // good
var totalScore = this.reviewScore + ' total score';

• 对于数字转换,使用parseInt,而且要带着类型转换的基数。

• 如果parseInt成为你的瓶颈,处于性能原因,需要你使用“位移”操作。那么请写下注释解释你这样做的原因。

var inputValue = '4';

// bad
var val = new Number(inputValue); // bad
var val = +inputValue; // bad
var val = inputValue >> 0; // bad
var val = parseInt(inputValue); // good
var val = Number(inputValue); // good
var val = parseInt(inputValue, 10); // good
/**
* parseInt 使我的代码变慢.
* 为了提高速度,使用位移操作让字符串强制转化为数字。
*/
var val = inputValue >> 0;

• 布尔

var age = 0;

// bad
var hasAge = new Boolean(age); // good
var hasAge = Boolean(age); // good
var hasAge = !!age;
Constructors
 
 • 用方法扩展对象,而不是用一个新对象。
function Jedi() {
console.log('new jedi');
} // bad
Jedi.prototype = {
fight: function fight() {
console.log('fighting');
}, block: function block() {
console.log('blocking');
}
}; // good
Jedi.prototype.fight = function fight() {
console.log('fighting');
}; Jedi.prototype.block = function block() {
console.log('blocking');
};
  • 让对象的方法return this,这样有利于方法的链锁操作。
 
// bad
Jedi.prototype.jump = function() {
this.jumping = true;
return true;
}; Jedi.prototype.setHeight = function(height) {
this.height = height;
}; var luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20) // => undefined // good
Jedi.prototype.jump = function() {
this.jumping = true;
return this;
}; Jedi.prototype.setHeight = function(height) {
this.height = height;
return this;
}; var luke = new Jedi(); luke.jump()
.setHeight(20);

• 我们可以自定义一个toString()方法。——要确保它能正常运行,而且不会产生其他影响。

function Jedi(options) {
options || (options = {});
this.name = options.name || 'no name';
} Jedi.prototype.getName = function getName() {
return this.name;
}; Jedi.prototype.toString = function toString() {
return 'Jedi - ' + this.getName();
};

js 代码风格(2)的更多相关文章

  1. 大神的JS代码风格指南

    js代码风格指南:1.缩进使用空格,不要用制表符2.必须用分号3.暂时不用ES6(modules)例如export和import命令4.不鼓励(不禁止)水平对齐5.少用var 都应该使用const或者 ...

  2. Google HTML/CSS/JS代码风格指南

    JS版本参见:http://www.zhangxinxu.com/wordpress/2012/07/google-html-css-javascript-style-guides/ HTML/CSS ...

  3. JS代码风格自动规整工具Prettier

    问题背景 通常使用 ESLint做代码风格检查检查, 和部分代码质量检查. 但是使用ESLint在入库时候, 会产生很多的代码修正工作, 需要开发者一个一个的修改. 如果很多,并且时间紧迫,甚是尴尬. ...

  4. JS代码风格指南

    一.基本格式 缩进 建议每级4个空格,可以给编辑器设置tab = 4个空格,自动转换 分号 不要省略分号,防止ASI(自动插入分号)错误 行宽 每行代码不超过80个字符,过长应该用操作符手动断行 断行 ...

  5. highlight.js代码风格引入方法

    <link href="https://cdn.bootcss.com/highlight.js/9.15.10/styles/darcula.min.css" rel=&q ...

  6. js代码风格之链式结构

    <div class="box"> <ul class="menu"> <li class="level1"& ...

  7. [Js代码风格]浅析模块模式

    1.实例解释模块模式 简明扼要的说,经典的模块模式指的定义一个立即执行的匿名函数.在函数中定义私有函数和私有变量并且返回一个包含公共变量和公共函数作为属性和方法的匿名对象. var classicMo ...

  8. Django之代码风格

    1 代码风格 稍微关注一下下面这些代码标准风格指导规则将会对你大有益处,我们高度建议你通读词章,即便你此时可能正想跳过它. 1.1 让你的代码保持可读性的重要性 代码在读方面的重要性胜过写.一个代码块 ...

  9. .NET 项目代码风格要求

    原文:http://kb.cnblogs.com/page/179593/ 项目代码风格要求 PDF版下载:项目代码风格要求V1.0.pdf 代码风格没有正确与否,重要的是整齐划一,这是我拟的一份&l ...

随机推荐

  1. JS判断一个字符串是否包含一个子串函数.

    微信小程序 JS判断一个字符串是否包含一个子串函数. //str 字符串,name子串     contains:function(str,name){         if(str.indexOf( ...

  2. v-for设置键值 key

    总是用 key 配合 v-for.在组件上_总是_必须用 key 配合 v-for,以便维护内部组件及其子树的状态. <ul> <li v-for="todo in tod ...

  3. SQLiteOpenHelper 源码

    package com.tongyan.common.db; /** * Copyright (C) 2007 The Android Open Source Project * * Licensed ...

  4. ICP备案的一些tips~

    1)一个单位是一个备案主体,只能有一个主体备案号: 2)一个企业下面可以有多个网站,依次在备案号后加-1 -2,以此类推,也叫网站备案号,每个网站只能有一个网站备案号.(所谓网站,不是指域名,也不是i ...

  5. CXF 调用方式——动态创建客户端(调用稳定版本号为2.7.18)

    今天用动态创建客户端的方式调用webservice,报了这样一个错: 2017-01-05 20:51:46,029 DEBUG main org.apache.cxf.common.logging. ...

  6. Lr_debug_message,Lr_output_message,Lr_error_message,Lrd_stmt,Lrd_fetch

    今天在群里,问了 Lr_debug_message,Lr_output_message,Lr_error_message,Lrd_stmt,Lrd_fetch.下 面我整理了下Lr_debug_mes ...

  7. FIS3项目构建

    概述 FIS3采取了类似CSS语法一样的配置风格,易于理解与上手.FIS3 是面向前端的工程构建工具.解决前端工程中性能优化.资源加载(异步.同步.按需.预加载.依赖管理.合并.内嵌).模块化开发.自 ...

  8. 【PHP原生】获取字符串所有汉字首字母和首个汉字首字母

    1.废话不多说,看代码,获取字符串汉字首字母,兼容GBK和UTF-8 <?php //获取单个汉字拼音首字母.注意:此处不要纠结.汉字拼音是没有以U和V开头的 function getfirst ...

  9. Javascript 判断网页横竖屏

    本篇文章由:http://xinpure.com/javascript-to-determine-page-anyway-screen/ Html5 流行至今,自适应的网站已经多如牛毛,但是横竖屏的切 ...

  10. Linux su命令参数及用法详解--Linux切换用户命令

    建议大家切换用户的时候 使用  su -  root  这样,否则可能发现某些命令执行不了 关于su .su - 及 sudo的区别 请往下看 1.命令作用 su的作用是变更为其它使用者的身份,超级用 ...