W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
13.1?一直使用?const
?來(lái)聲明變量,如果不這樣做就會(huì)產(chǎn)生全局變量。我們需要避免全局命名空間的污染。地球隊(duì)長(zhǎng)已經(jīng)警告過我們了。(譯注:全局,global 亦有全球的意思。地球隊(duì)長(zhǎng)的責(zé)任是保衛(wèi)地球環(huán)境,所以他警告我們不要造成「全球」污染。)
// bad
superPower = new SuperPower();
// good
const superPower = new SuperPower();
13.2?使用?var
?聲明每一個(gè)變量。
為什么?增加新變量將變的更加容易,而且你永遠(yuǎn)不用再擔(dān)心調(diào)換錯(cuò)?
;
?跟?,
。
// bad
const items = getItems(),
goSportsTeam = true,
dragonball = 'z';
// bad
// (compare to above, and try to spot the mistake)
const items = getItems(),
goSportsTeam = true;
dragonball = 'z';
// good
const items = getItems();
const goSportsTeam = true;
const dragonball = 'z';
13.3?將所有的?const
?和?let
?分組
為什么?當(dāng)你需要把已賦值變量賦值給未賦值變量時(shí)非常有用。
// bad
let i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;
// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;
13.4?在你需要的地方給變量賦值,但請(qǐng)把它們放在一個(gè)合理的位置。
為什么?
let
?和?const
?是塊級(jí)作用域而不是函數(shù)作用域。
// good
function() {
test();
console.log('doing stuff..');
//..other stuff..
const name = getName();
if (name === 'test') {
return false;
}
return name;
}
// bad - unnecessary function call
function(hasName) {
const name = getName();
if (!hasName) {
return false;
}
this.setFirstName(name);
return true;
}
// good
function(hasName) {
if (!hasName) {
return false;
}
const name = getName();
this.setFirstName(name);
return true;
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: