這兩個功能的相似之處在於它們都是不可分配的。
能具體解釋一下嗎?
在這篇文章中,我將分享它們之間的差異。
在這種情況下,hisName 是一個不能重新分配的變數。
const hisName = 'Michael Scofield' hisName = 'Lincoln Burrows' // → ❌ Cannot assign to 'hisName' because it is a constant.
但是,您可以重新指派屬性。
const hisFamily = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ⭕️ hisFamily = { mother: 'Christina Rose Scofield' } // → ❌ Cannot assign to 'hisFamily' because it is a constant.
例如,如果嘗試用readonly給brother賦值,就會發生編譯錯誤。
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ❌ Cannot assign to 'brother' because it is a read-only property.
另一方面,允許對變數本身進行賦值。
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily = { brother: '' } // → ⭕️
const 使變數本身不可分配,而 readonly 使屬性不可分配。
透過結合 const 和 readonly,您可以建立一個對象,其中變數本身和對象的屬性都是不可變的。
const hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // ❌ Cannot assign to 'brother' because it is a read-only property. hisFamily = { brother: '' } // ❌ Cannot assign to 'hisFamily' because it is a constant.
快樂編碼☀️
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3