Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重覆宣告參數等幾點 coding style 建議 #19

Open
GHolk opened this issue Mar 14, 2018 · 8 comments
Open

重覆宣告參數等幾點 coding style 建議 #19

GHolk opened this issue Mar 14, 2018 · 8 comments

Comments

@GHolk
Copy link
Member

GHolk commented Mar 14, 2018

不要宣告和參數同名的變數

function redeclareArgument(body) {
  var body = JSON.parse(body) // 重覆宣告了
  body = JSON.parse(body) // 可以直接覆寫是
  const json = JSON.parse(body) // 取一個新名字更好
}

不要在 block 裡宣告函數

記得 block 裡不能宣告函數,只能用函數表達式。
和不能在 block 裡用 var 宣告變數差不多。
雖然沒什麼關係,但我會盡量避免。

if (!err) {
  // 這樣不太 ok
  function recurElseListInside() {
  }
  recurElseListInside([])
}
// 宣告在外面比較好
function recurElseListOutside() {
}

為什麼要用 snake_case

javascript 統一用 camelCase 好嗎?
playList 裡怎麼一堆 song_list song_data

@d4n1elchen
Copy link
Contributor

不要宣告和參數同名的變數

下次 commit 會修正,之前有想過要改,但是改完覺得看起來很不舒服就改回去了(?

不要在 block 裡宣告函數

差別在哪??

為什麼要用 snake_case

之前的習慣是暫存資料會用 snake_case,song_data song_list 只是用來架構準備要傳出去的資料結構而已。

@GHolk
Copy link
Member Author

GHolk commented Mar 15, 2018

block 裡宣告就和 var 一樣,
會被提升到全域.
我也不知道有什麼不好.
標準裡好像也不能在 block裡用 var宣告,
會被視為在函數裡宣告,
( var都會被提升到函數頂)
在 block裡賦值.

@d4n1elchen
Copy link
Contributor

剛剛查了一下 function declare 會被限制在 block 裡面

A function declaration is also limited in scope inside the block where the declaration occurs

foo('outside');  // TypeError: foo is not a function
{
  function foo(location) {
   console.log('foo is called ' + location);
  }
  foo('inside'); // works correctly and logs 'foo is called inside' 
}

[ref]

@GHolk
Copy link
Member Author

GHolk commented Mar 16, 2018

原來改了

@Yuessiah
Copy link
Member

其實你們兩個都對一半

{
  function foo(location) {
   console.log('foo is called ' + location);
  }
  foo('inside'); // works correctly and logs 'foo is called inside' 
}

foo('outside');  // It works!

@d4n1elchen
Copy link
Contributor

JavaScript 很棒吧

@GHolk
Copy link
Member Author

GHolk commented Mar 16, 2018

答案是看你有沒有 "use strict"
非嚴格模式好像會變成:

var hey
if (true) {
  hey = function () {
  }
}

你們自己試吧:

"use strict" // 把這行刪掉就是非嚴格模試

console.log(typeof hey)

if (true) {
    function hey() {
        return hey
    }
}

console.log(typeof hey)

@d4n1elchen
Copy link
Contributor

總之function會被限制在block中,符合該段程式的需求,無須修改,找時間把 Coding Style 整合之後再把這篇關掉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants