JavaScript has multiple properties Configurable,writable,enumerable,value,get and set in the object to control the behavior of the property. The same ES5 also has several methods to specify the behavior of the object. We know that the objects in JavaScript are shareable and can be extended by default:
//一旦将对象设置防篡改,就不能撤销了//众所周知,一般的对象是可以随意拓展的var person = {name:‘liufang‘22;document.write(person.age+"<br>");//22
We can add, delete, or modify other properties or methods. But this can also lead to problems, such as when many people develop, some attributes are artificially modified, causing engineering problems. This has led to the birth of anti-tampering objects. Tamper-resistant objects have three levels, namely non-expanding objects, sealed objects, and frozen objects .
Non-scalable objects
First of all, it is not possible to expand the object, you can make the newly added property invalid by setting the normal object to a non-expanding object:
//防拓展对象Object.preventExtensions(person);//设置为防拓展对象‘ff‘;document.write(person.smallName+"<br>");//undefined//说明不能添加新属性//检测是否为可拓展对象document.write(Object.isExtensible(person)+"<br>");//false//虽然防拓展对象不能添加属性,但是可以删除属性delete person.age;document.write(person.age+"<br>");//undefined ,已经删除成功
As you can see, although non-scalable objects prevent new attributes from being added, you cannot prevent others from deleting them, and of course you cannot prevent them from being modified. So the second level of the sealed object is drawn.
Sealed objects
The
Sealed object is to add a rule on the basis of a non-scalable object, that is, the property cannot be deleted.
//sealed object //cannot remove var people = {name: On a non-scalable basis. ' Liufang ' }; object . Seal (people); //to seal the object delete people.name;document.write (people.name+ "< Br> "); //liufang, stating that people.name = ; //although cannot be deleted, but can modify document.write (People.name+); //TYQ, indicating successful modification //detect document.write (object . issealed (People ) + "<br>" ); //true
As you can see, the sealed object, although it prevents the deletion, but still cannot prevent the modification, so there is the highest level of restrictions, that is, frozen objects.
Freeze objects
Objects that are frozen cannot be expanded or deleted or modified.
//冻结对象//不能拓展,不能删除,不能修改var man = {name:‘tyq‘};Object.freeze(man);//检测document.write(Object.isFrozen(man));//true
The last thing to note is that once the object is set to tamper with the object, it cannot be undone, so it needs to be considered carefully.
This example demo address: Demo
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Deep understanding of JavaScript's tamper-resistant objects