為什么這會記錄 1 ?這讓我很困惑,誰能解釋一下?
(function(){
var hello = () => {
console.log(1);
}
function hello () {
console.log(2);
}
return hello()
})()
uj5u.com熱心網友回復:
函式宣告(function functionName( 以=.
它是一個箭頭函式這一事實并不特別重要——function在同一點進行賦值會產生相同的結果。
(function(){
var hello = function() {
console.log(1);
}
function hello () {
console.log(2);
}
return hello()
})()
您的代碼相當于
(function(){
// hello identifier gets created at the very beginning
var hello;
// hoisted function declaration assigns to `hello`:
hello = function hello () {
console.log(2);
}
// assignment with =, not hoisted, assigns to `hello`
hello = () => {
console.log(1);
}
return hello()
})()
我建議至少使用 ES2015 語法,這將有助于防止您發生此類事故 - 如果您使用let或,它將禁止重新宣告變數const。
(function(){
let hello = () => {
console.log(1);
}
function hello () {
console.log(2);
}
return hello()
})()
uj5u.com熱心網友回復:
因為:
- 函式宣告在與
var宣告相同的系結環境中創建識別符號(更具體地說,“系結”) var已經存在的系結的宣告不是錯誤- 函式宣告在進入函式或全域范圍(“提升”)時被處理,因此它們首先分配給系結
因此,您的代碼正在創建一個系結,為其分配一個宣告的函式,然后用箭頭函式覆寫該值。有效:
(function(){
// Declaration of the var-scoped binding happens first
var hello;
// Then the function declaration is processed, assigning
// the function to the binding
hello = function hello() {
console.log(2);
};
// Then the step-by-step code begins and processes
// the assignment
hello = () => {
console.log(1);
};
return hello();
})();
旁注:var已被有效棄用,沒有理由在現代代碼中使用它。相反,使用letor const。他們有更理性的行為:
- 它們是塊作用域的,而不是函式作用域或全域作用域的(除非它們出現在函式或全域作用域的頂層)
- 重復宣告是一個錯誤(包括會與- 樣式宣告(如函式宣告)沖突的
letor宣告)constvar - 在全域范圍內,它們存在于嵌套在全域
var范圍內的內部范圍中,并且它們不會在全域物件上創建屬性
你的例子會給你一個很好的,有用的錯誤letor const:
(function(){
let hello = () => {
console.log(1);
};
function hello () {
console.log(2);
}
return hello();
})()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405945.html
標籤:
上一篇:React-復選框的問題
