2
剛剛在最近的question I was looking at中遇到以下內容,我很好奇爲什麼var name
和const name
提供不同的輸出。運行下面的代碼片段以查看我的意思。const vs var和window.name屬性
如果有什麼關係name
是一個window
對象的屬性,然後重新申報/定義name
與const
應導致一個錯誤,我覺得。但是,在下面的示例中,const
允許將name
重新聲明爲數組,而var
不允許。
var name = ['one', 'two', 'three', 'four', 'five'];
for (var i=0; i < name.length; i++){
document.write(name[i] + '<br>');
}
const name = ['one', 'two', 'three', 'four', 'five'];
for (var i=0; i < name.length; i++){
document.write(name[i] + '<br>');
}
那麼,爲什麼const
讓我劫持的window.name
財產並重新分配它作爲一個數組?但var
不允許重新分配(仍然爲默認string
)?或者我只是以錯誤的方式看待它?
也應該注意,出於同樣的原因,'let'就像'const'一樣。 – Barmar
Gotcha。我知道'let',但不知道'const'遵循相同的約束。每天學些新東西。 – Marcus