JavaScript防篡改对象

preventExtensions:不能增,能删改
seal:不能增删,能改
freeze:不能增删改

对象属性
preventExtensions X
seal X X
freeze X X X

不可扩展对象preventExtensions

Object.preventExtensions不能增,能删改

var obj = {a:1,b:2};
Object.preventExtensions(obj);
obj.c = 3;
console.log(obj.c); // undefined
delete obj.a;
console.log(obj); // {b: 2} 删除成功
obj.b = 'hello'
console.log(obj); // {b: "hello"} 修改成功

检测是否不可扩展Object.isExtensible(obj)

(false是不可扩展,true是正常对象)

Object.isExtensible(obj);// false

密封的对象seal

Object.seal不能增删,能改

var obj = {a:1,b:2};
Object.seal(obj);
obj.c = 3;
console.log(obj.c); // undefined
delete obj.a;
console.log(obj); // {a:1,b:2} 删除失败
obj.b = 'hello'
console.log(obj); // {a:1,b: "hello"} 修改成功

检测是否密封Object.isSealed(obj)

(false是正常,true是已经密封了)

Object.isSealed(obj);// true

冻结的对象freeze

Object.freeze不能增删改

var obj = {a:1,b:2};
Object.freeze(obj);
obj.c = 3;
console.log(obj.c); // undefined
delete obj.a;
console.log(obj); // {a:1,b:2} 删除失败
obj.b = 'hello'
console.log(obj); // {a:1,b:2} 修改失败

检测是否冻结Object.isFrozen(obj)

(false是正常,true是已经冻结了)

Object.isFrozen(obj);// true
posted @ 2020-06-30 14:50  春风自是人间客  阅读(145)  评论(0编辑  收藏  举报