读书人

Javascript 作派向导

发布时间: 2013-09-05 16:02:06 作者: rapoo

Javascript 风格向导

var foo = 1,    bar = foo;bar = 9;console.log(foo, bar); // => 1, 9

? 复合类型:我们通过`引用`对值进行间接访问。

var foo = [1, 2],    bar = foo;bar[0] = 9;console.log(foo[0], bar[0]); // => 9, 9

 

// badvar superman = {  class: 'superhero',  default: { clark: 'kent' },  private: true};// goodvar superman = {  klass: 'superhero',  defaults: { clark: 'kent' },  hidden: true};

var someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');
var len = items.length,    itemsCopy = [],    i;// badfor (i = 0; i < len; i++) {  itemsCopy[i] = items[i];}// gooditemsCopy = items.slice();

// badvar name = "Bob Parr";// goodvar name = 'Bob Parr';// badvar fullName = "Bob " + this.lastName;// goodvar fullName = 'Bob ' + this.lastName;

? 超过80个字符的字符串,我们使用串联符号(\),让字符串多行显示。

? 注意:如果过度使用带串联符号的字符可能会影响到性能。

Javascript 作派向导 

// badvar errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badvar errorMessage = 'This is a super long error that \was thrown because of Batman. \When you stop to think about \how Batman had anything to do \with this, you would get nowhere \fast.';// goodvar errorMessage = 'This is a super long error that ' +  'was thrown because of Batman.' +  'When you stop to think about ' +  'how Batman had anything to do ' +  'with this, you would get nowhere ' +  'fast.';

  

? 当我们在编程的时候,需要拼接出一个字符串,我们可以使用Array#join 代替字符串连接。尤其是对IE浏览器。

var items,    messages,    length, i;messages = [{    state: 'success',    message: 'This one worked.'},{    state: 'success',    message: 'This one worked as well.'},{    state: 'error',    message: 'This one did not work.'}];length = messages.length;// badfunction inbox(messages) {  items = '<ul>';  for (i = 0; i < length; i++) {    items += '<li>' + messages[i].message + '</li>';  }  return items + '</ul>';}// goodfunction inbox(messages) {  items = [];  for (i = 0; i < length; i++) {    items[i] = messages[i].message;  }  return '<ul><li>' + items.join('</li><li>') + '</li></ul>';}

// anonymous function expressionvar anonymous = function() {  return true;};// named function expressionvar named = function named() {  return true;};// immediately-invoked function expression (IIFE)(function() {  console.log('Welcome to the Internet. Please follow me.');})();

? 绝对不要在非函数块(if,while)申明一个函数。我们可以把函数申明变成一个函数表达式。

// badif (currentUser) {  function test() {    console.log('Nope.');  }}// goodif (currentUser) {  var test = function test() {    console.log('Yup.');  };}

? 绝对不要把一个参数命名为arguments,arguments参数是函数作用域内给出的一个特殊变量,如果你把参数命名为arguments,那么这个参数就会覆盖它原有的特殊变量。

// badfunction nope(name, options, arguments) {  // ...stuff...}// goodfunction yup(name, options, args) {  // ...stuff...}

总结  这些很多是大家都比较清楚的,平时经常用,我只是强调一下,让大家再复习一下。

读书人网 >JavaScript

热点推荐