这两个功能的相似之处在于它们都是不可分配的。
能具体解释一下吗?
在这篇文章中,我将分享它们之间的区别。
在这种情况下,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