- 除了三目運(yùn)算,if,else等禁止簡寫
// 正確的書寫
if (true) {
alert(name);
}
console.log(name);
// 不推薦的書寫
if (true)
alert(name);
console.log(name);
// 不推薦的書寫
if (true)
alert(name);
console.log(name)
- 在需要以{}閉合的代碼段前增加換行,如:for if
// 沒有換行,小的代碼段無法區(qū)分
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; ++i) {
p = wl[i];
type = Y.Lang.type(r[p]);
if (s.hasOwnProperty(p)) {
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (ov || !(p in r)) {
r[p] = s[p];
}
}
}
}
// 有了換行,邏輯清楚多了
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; ++i) {
p = wl[i];
type = Y.Lang.type(r[p]);
if (s.hasOwnProperty(p)) {
// 處理merge邏輯
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (ov || !(p in r)) {
r[p] = s[p];
}
}
}
}
換行可以是空行,也可以是注釋
- 使用Function進(jìn)行類的定義,不推薦繼承,如需繼承采用成熟的類庫實(shí)現(xiàn)繼承
// 類的實(shí)現(xiàn)
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
alert(this.name);
};
var me = new Person("Nicholas");
// 將this放到局部變量self
function Persion(name, sex) {
var self = this;
self.name = name;
self.sex = sex;
}
平時(shí)咱們寫代碼,基本都是小程序,真心用不上什么繼承,而且繼承并不是JS的擅長的語言特性,盡量少用。如果非要使用的話,注意一點(diǎn):
function A(){
//...
}
function B(){
//...
}
B.prototype = new A();
B.prototype.constructor = B; //原則上,記得把這句話加上
繼承從原則上來講,別改變他的構(gòu)造函數(shù),否則這個(gè)繼承就顯得很別扭了~ - 使用局部變量緩存反復(fù)查找的對(duì)象(包括但不限于全局變量、dom查詢結(jié)果、作用域鏈較深的對(duì)象)
// 緩存對(duì)象
var getComment = function() {
var dom = $("#common-container"), // 緩存dom
appendTo = $.appendTo, // 緩存全局變量
data = this.json.data; // 緩存作用域鏈較深的對(duì)象
}
//當(dāng)需要緩存this時(shí)必須使用self變量進(jìn)行緩存
// 緩存this
function Row(name) {
var self = this;
self.name = name;
$(".row").click(function() {
self.getName();
});
}
self是一個(gè)保留字,不過用它也沒關(guān)系。在這里,看個(gè)人愛好吧,可以用_this, that, me等這些詞,都行,但是團(tuán)隊(duì)開發(fā)的時(shí)候統(tǒng)一下比較好。 - 使用eval,采取$.parseJSON
三個(gè)原因:
有注入風(fēng)險(xiǎn),尤其是ajax返回?cái)?shù)據(jù)
不方便debug效率低,eval是一個(gè)執(zhí)行
效率很低的函數(shù)
建議: 使用new Function來代替eval的使用,最好就別用。
更多建議: