JavaScript中的Object.freeze與const之間的區(qū)別(譯)

原文:The differences between Object.freeze() vs Const in JavaScript
作者:Bolaji Ayodeji
本文經(jīng)授權(quán)翻譯轉(zhuǎn)載,版權(quán)歸原作者所有!

image.png
image.png

自ES6發(fā)布以來,ES6給JavaScript帶來了一些新特性和方法。對于JavaScript開發(fā)者來說,這些特性能夠很好地改善了我們的工作流程以及工作效率,其中的特性就包括 Object.freeze() 方法和 const 。

一些開發(fā)人員特別是新手們會認(rèn)為這兩個功能的工作方式是一樣的,但其實(shí)并不是。 讓我來告訴你Object.freeze()const 是如何不同的。

綜述

constObject.freeze() 完全不同。

  • const 的行為像 let 。它們唯一的區(qū)別是, const 定義了一個無法重新分配的變量。 通過 const 聲明的變量是具有塊級作用域的,而不是像 var 聲明的變量具有函數(shù)作用域。
  • Object.freeze() 接受一個對象作為參數(shù),并返回一個相同的不可變的對象。這就意味著我們不能添加,刪除或更改對象的任何屬性。

可變對象的屬性能夠進(jìn)行更改,而不可變對象在創(chuàng)建對象后不能更改其屬性。

例子

const

const user = 'Bolaji Ayodeji'
user = 'Joe Nash'

這個例子會拋出一個Uncaught TypeError,因?yàn)槲覀冋趪L試重新分配使用const關(guān)鍵字聲明的變量user,這樣做是無效的。

image.png
image.png

這個例子中使用 let 或者 var 聲明是能夠正常工作的,但是使用 const 并不能。

const 的問題

使用const聲明的對象僅能阻止其重新分配,但是并不能使其聲明的對象具有不可變性(能夠阻止更改其屬性)。

參考以下代碼,我們使用const關(guān)鍵字聲明了一個變量,并為其分配了一個名為user的對象。

const user = {
  first_name: 'bolaji',
  last_name: 'ayodeji',
  email: 'hi@bolajiayodeji.com',
  net_worth: 2000
}
user.last_name = 'Samson';
// this would work, user is still mutable!
user.net_worth = 983265975975950;
// this would work too, user is still mutable and getting rich :)!
console.log(user);  // user is mutated
image.png
image.png

盡管我們無法重新分配這個名為 user 的變量,但是我們?nèi)匀豢梢愿淖兤鋵ο蟊旧怼?/p>

const user = {
  user_name: 'bolajiayodeji'
}
// won't work
image.png
image.png

我們肯定希望對象具有無法修改或刪除的屬性。 const 無法實(shí)現(xiàn)這樣的功能,但是 Object.freeze 可以。

Object.freeze()

要禁用對象的任何更改,我們需要使用 Object.freeze()

const user = {
  first_name: 'bolaji',
  last_name: 'ayodeji',
  email: 'hi@bolajiayodeji.com',
  net_worth: 2000
}
Object.freeze(user);
user.last_name = 'Samson';
// this won't work, user is still immutable!
user.net_worth = 983265975975950;
// this won't work too, user is still immutable and still broke :(!
console.log(user);  // user is immutated
image.png
image.png

具有嵌套屬性的對象實(shí)際上并未凍結(jié)

Object.freeze 只是做了層淺凍結(jié),當(dāng)遇到具有嵌套屬性的對象的時候,我們需要遞歸Object.freeze 來凍結(jié)具有嵌套屬性的對象。

const user = {
  first_name: 'bolaji',
  last_name: 'ayodeji',
  contact: {
    email: 'hi@bolajiayodeji.com',
    telephone: 08109445504,
  }
}

Object.freeze(user);
user.last_name = 'Samson';
// this won't work, user is still immutable!
user.contact.telephone = 07054394926;
// this will work because the nested object is not frozen
console.log(user);
image.png
image.png

因此,當(dāng)具有嵌套屬性的對象時, Object.freeze() 并不能完全凍結(jié)對象。

要完全凍結(jié)具有嵌套屬性的對象,您可以編寫自己的庫或使用已有的庫來凍結(jié)對象,如Deepfreezeimmutable-js

結(jié)論

constObject.freeze() 并不同, const 是防止變量重新分配,而 Object.freeze() 是使對象具有不可變性。

感謝閱讀,干杯!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容