在JavaScript中,是否可以存在某些属性,使得它们只能由其附加到的对象内部的代码修改,并且是只读的,并且可以防止其对象外部的代码删除它们?
答案 0 :(得分:0)
是的,一种可能性是使用显示模块模式-在模块内部保留要保留的私有变量,并公开返回该变量的getter。查看评论:
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