今天主要是来讲讲关于js最底层的基础知识,把握每个细节,做一个真正了解前端的前端。
主要涵盖注释,空白,逗号,分号,类型转化,命名规则, 请君侧耳听
一.注释
1.使用 /* … / 作为多行注释。包含描述、指定所有参数和返回值的类型和值
// 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;
}
2.使用 // 作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行
// 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;
}
3.使用 // FIXME: 标注问题
function Calculator() {
// FIXME: shouldn't use a global here
total = 0;
return this;
}
4.使用 // TODO: 标注问题的解决方式
function Calculator() {
// TODO: total should be configurable by an options param
this.total = 0;
return this;
}
二.空白
1.使用 2 个空格作为缩进
// bad
function () {
∙∙∙∙var name;
}
// bad
function () {
∙var name;
}
// good
function () {
∙∙var name;
}
2.在大括号前放一个空格
// bad
function test(){
console.log('test');
}
// good
function test() {
console.log('test');
}
// bad
dog.set('attr',{
age: '1 year',
breed: 'Bernese Mountain Dog'
});
// good
dog.set('attr', {
age: '1 year',
breed: 'Bernese Mountain Dog'
});
3.在控制语句(if、while 等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格
// bad
if(isJedi) {
fight ();
}
// good
if (isJedi) {
fight();
}
// bad
function fight () {
console.log ('Swooosh!');
}
// good
function fight() {
console.log('Swooosh!');
}
4.使用空格把运算符隔开
// bad
var x=y+5;
// good
var x = y + 5;
5.在使用长方法链时进行缩进。使用前面的点 . 强调这是方法调用而不是新语句
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('.selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
.attr('width', (radius + margin) * 2).append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
.call(tron.led);
// good
var leds = stage.selectAll('.led')
.data(data)
.enter().append('svg:svg')
.classed('led', true)
.attr('width', (radius + margin) * 2)
.append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
.call(tron.led);
6.在块末和新语句前插入空行
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function () {
},
bar: function () {
}
};
return obj;
// good
var obj = {
foo: function () {
},
bar: function () {
}
};
return obj;
3.逗号
1.行首逗号: 不需要
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
once,
upon,
aTime
];
// bad
var hero = {
firstName: 'Bob'
, lastName: 'Parr'
, heroName: 'Mr. Incredible'
, superPower: 'strength'
};
// good
var hero = {
firstName: 'Bob',
lastName: 'Parr',
heroName: 'Mr. Incredible',
superPower: 'strength'
};
2.额外的行末逗号:不需要。这样做会在 IE6/7 和 IE9 怪异模式下引起问题
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
var heroes = [
'Batman',
'Superman',
];
// good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
var heroes = [
'Batman',
'Superman'
];
4.分号
1.合理使用分号
// bad
(function () {
var name = 'Skywalker'
return name
})()
// good
(function () {
var name = 'Skywalker';
return name;
})();
// good (防止函数在两个 IIFE 合并时被当成一个参数
;(function () {
var name = 'Skywalker';
return name;
})();
5.类型转换
1.字符串:
// => 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';
2.使用 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);
3.小心使用位操作运算符。数字会被当成64位值,但是位操作运算符总是返回32位的整数(source)。位操作处理大于32位的整数值时还会导致意料之外的行为。讨论。最大的32位整数是2,147,483,647
2147483647 >> 0 // => 2147483647
2147483648 >> 0 // => -2147483648
2147483649 >> 0 // => -2147483647
4.布尔
var age = 0;
// bad
var hasAge = new Boolean(age);
// good
var hasAge = Boolean(age);
// good
var hasAge = !!age;
6.命名规则
1.避免单字母命名。命名应具备描述性
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
2.使用驼峰式命名对象、函数和实例
// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
var o = {};
function c() {}
// good
var thisIsMyObject = {};
function thisIsMyFunction() {}
3.使用帕斯卡式命名构造函数或类
// bad
function user(options) {
this.name = options.name;
}
var bad = new user({
name: 'nope'
});
// good
function User(options) {
this.name = options.name;
}
var good = new User({
name: 'yup'
});
4.不要保存 this 的引用。使用 Function#bind
// bad
function () {
var self = this;
return function () {
console.log(self);
};
}
// bad
function () {
var that = this;
return function () {
console.log(that);
};
}
// bad
function () {
var _this = this;
return function () {
console.log(_this);
};
}
// good
function () {
return function () {
console.log(this);
}.bind(this);
}
5.给函数命名。这在做堆栈轨迹时很有帮助
// bad
var log = function (msg) {
console.log(msg);
};
// good
var log = function log(msg) {
console.log(msg);
};