Javascript 保护对象属性不被控制台覆盖
我试图保护对象的属性不被控制台覆盖。e、 g.我有一个person对象,其中有一个过敏列表作为属性。过敏症列表应该可以修改,但是它应该始终是一个列表,如果用户试图编写“person.allergies=”废话“,则应该抛出一个错误 我试过查看Object.freeze()和Object.seal(),但无法实现这一目的,因为我认为没有办法解冻对象Javascript 保护对象属性不被控制台覆盖,javascript,node.js,oop,Javascript,Node.js,Oop,我试图保护对象的属性不被控制台覆盖。e、 g.我有一个person对象,其中有一个过敏列表作为属性。过敏症列表应该可以修改,但是它应该始终是一个列表,如果用户试图编写“person.allergies=”废话“,则应该抛出一个错误 我试过查看Object.freeze()和Object.seal(),但无法实现这一目的,因为我认为没有办法解冻对象 class Person { constructor(name){ this.name = name this
class Person {
constructor(name){
this.name = name
this.allergies = []
}
addAllergy(allergy){
this.allergies.push(allergy)
return allergy
}
}
ben = new Person('Ben') // Creating a new Object
ben.addAllergy('Dairy') // Giving the object a new allergy
ben.allergies // Should output ['Dairy']
ben.allergies = 'Soy' // Should make no changes to ben object.
您可以使用以下内容将
allergies
设置为不可写属性:
班级人员{
建造师(姓名){
this.name=name
Object.defineProperty(这是“过敏症”{
值:[],
可写:false
});
}
过敏(过敏){
这个。过敏。推(过敏)
回归过敏
}
}
ben=新人('ben')//创建新对象
ben.addAllergy('Dairy')//给对象一个新的变态反应
console.log(ben.allergies)//应该输出['Dairy']
ben.allergies='Soy'//不应更改ben对象。
本·阿达尼(‘花生’)
console.log(ben.allergies)//静态数组
使用私有属性:
class Person {
#allergies;
constructor(name){
this.name = name
this.#allergies = []
}
addAllergy(allergy){
this.#allergies.push(allergy)
return allergy
}
get allergies() {
// you might want to deep clone it here
// to fully protect from changes the array behind
return this.#allergies;
}
set allergies(value) {
throw new Error('haha, I got you!');
}
}
ECMA标准中正在实现私有字段。你可以
今天就开始使用巴别塔7和第3阶段预设
你用10秒的时间击败了我:)最棒的是,你不能再重新定义属性了,只要它被定义了。您可以使用
Object.defineProperty(ben,'allergies',{get(){return'abc'}})打破原始帖子中的任何保护逻辑。
感谢您的解决方案。-使用Object.defineProperty将可写属性设置为false非常有效!非常感谢:)值是否由“控制台”写入并不重要,您无法区分这一点。要么是可写的,要么不是。你到底想实现什么,你想解决什么问题?对象。冻结ingben
(或任何其他Person
实例)不会使ben.allergies
列表不可修改。听起来这正是你想要的。但是我现在如何访问列表呢?@Bergi有一个getter,并且只有当你真的想将它暴露在对象之外时。查看更新