对象的不变性意味着我们不希望对象在创建后以任何方式更改(将它们设置为只读类型)。
假设我们需要定义一个 car 对象,并在整个项目中使用它的属性来执行操作。我们不能允许错误地修改任何数据。
const myTesla = {
maxSpeed: 155, batteryLife: 300, weight: 2300 }; |
Object.preventExtensions() 防止扩展
此方法可防止向现有对象添加新属性,preventExtensions() 是不可逆的操作,我们永远不能再向对象添加额外的属性。
Object.isExtensible(myTesla); // true
Object.preventExtensions(myTesla); Object.isExtensible(myTesla); // false myTesla.color = 'blue'; console.log(myTesla.color) // undefined |
Object.seal() 密封
它可以防止添加或删除属性,seal() 还可以防止修改属性描述符。
Object.isSealed(myTesla); // false
Object.seal(myTesla); Object.isSealed(myTesla); // true myTesla.color = 'blue'; console.log(myTesla.color); // undefined delete myTesla.batteryLife; // false console.log(myTesla.batteryLife); // 300 Object.defineProperty(myTesla, 'batteryLife'); // TypeError: Cannot redefine property: batteryLife |
Object.freeze() 冻结
它的作用与 Object.seal() 相同,而且它使属性不可写。
Object.isFrozen(myTesla); // false
Object.freeze(myTesla); Object.isFrozen(myTesla); // true myTesla.color = 'blue'; console.log(myTesla.color); // undefined delete myTesla.batteryLife; console.log(myTesla.batteryLife); // 300 Object.defineProperty(myTesla, 'batteryLife'); // TypeError: Cannot redefine property: batteryLife myTesla.batteryLife = 400; console.log(myTesla.batteryLife); // 300 |
注意:如果希望在尝试修改不可变对象时抛出错误,请使用严格模式。
以上就是js如何创建不可变的对象的详细内容,更多请关注网站的其它相关文章!
- 上一篇: 服务器是干什么用的?
- 下一篇: js生成1到100的随机数
- 最新文章
-
- phpcms v9无法更新url
- phpcms注册会员操作失败
- phpcms怎么修改模板
- phpcms添加内容报500错误的原因及解决方法
- linux服务器下phpcms提示hash数据验证失败的解决方法
- phpcms与phpsso通信失败的解决方法
- phpcms上传图片提示服务器安全认证错误的原因及解决方法
- phpcms v9更新栏目缓存失败的原因及解决方法
- phpcms v9后台登录提示验证码错误
- phpcms可以做什么?
- phpcms v9安装失败
- phpcms会员登录失败
- phpcms前台js获取不到cookie用户信息
- phpcms控制器不存在
- phpcms v9 php7可以运行吗
- phpcms js乱码怎么解决
- phpcms提示服务器安全认证错误
- phpcms php.ini在哪里
- phpcms phpsso验证码错误
- phpcms v9参数传递错误
- 热门文章
- 热门tag
- 随机tag