Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

创建不可变对象 #59

Open
lovelmh13 opened this issue May 30, 2021 · 0 comments
Open

创建不可变对象 #59

lovelmh13 opened this issue May 30, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

const immutable = { a: 1 }

// Object.defineProperty(immutable) 这个方法不可取,因为这个只能控制属性

// 方法 1 阻止对象扩展,不能再添加新属性,但是可以修改删除已有的属性
Object.preventExtensions(immutable)
immutable.a = 2

// 方法 2 冷冻对象, 冻结后就不能再被扩展了。被冻结的对象的原型也不能被改变。如果对象的属性是一个对象,那么这个对象属性可以被修改
Object.freeze(immutable)

immutable.a = 1
immutable.__proto__ = String.prototype // Uncaught TypeError: [object Object] is not extensible

// 方法 3 密封, 阻止添加新属性,同时将现有属性标记为不可配置(不可以对原有属性通过 defineProperty 重新配置 ),原属性本来就可以修改的话,依然可以修改。除了修改原有属性以外,所有操作都会失败
Object.seal(immutable)

immutable.a = 2
delete immutable.a
immutable.b = 3

console.log(immutable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant