简体   繁体   English

可以在JavaScript中创建对对象外部代码只读的属性吗?

[英]Can properties that are read-only to code outside of an object be created in JavaScript?

在JavaScript中,是否可以存在某些属性,使得它们只能由其附加到的对象内部的代码修改,并且是只读的,并且可以防止其对象外部的代码删除它们?

Yes, one possibility is to use the revealing module pattern - keep the variables that you want to keep private and unalterable inside the module, and expose a getter that returns that variable. 是的,一种可能的方法是使用显示模块模式-将要保留的变量保持私有和不可更改的状态,并公开返回该变量的吸气剂。 See comments: 看评论:

 const counter = (() => { let num = 5; return { get num() { return num }, increment: () => num++, }; })(); console.log(counter.num); // 5 counter.num++; // Won't do anything, since num can only be changed from the inside console.log(counter.num); // Still 5 counter.increment(); // Calls the method internal to the object, which increments num console.log(counter.num); // 6 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM