ECMAScript 5引入了几种防止修改对象的方法。这些预防措施确保没有任何人意外或以其他方式更改对象的功能。
在此级别,不能添加任何新的属性或方法,但可以访问现有的属性或方法。这里可以删除相应的对象。Object.preventExtensions()是用于完成此任务的方法。这样可以防止将任何新属性添加到对象中。
<html> <body> <script> var object1 = { prop1: 1 }; Object.preventExtensions(object1); delete object1.prop1 // value got deleted try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); </script> </body> </html>
TypeError: Cannot define property prop2, object is not extensible undefined // deleted so undefined
它与防止扩展相同,此外,它不允许删除现有的属性或方法。为了完成此任务,使用了Object.seal()方法。
<html> <body> <script> var object1 = { prop1: 1 }; Object.seal(object1); object1.prop1 = 2; // value got changed delete object1.prop1; try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); // it gives value as 2 because of seal. </script> </body> </html>
TypeError: Cannot define property prop2, object is not extensible 2 // because of seal the value can't be deleated but got updated
除了Seal的功能之外,冻结甚至不允许访问现有属性。要冻结对象,我们使用 Object.freeze()方法。它还可以使对象不可变。
<html> <body> <script> var object1 = { prop1: 1 }; Object.freeze(object1); object1.prop1 = 2; // value got updated delete object1.prop1; // value got deleted try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); // it gives 1 as output despite value updated to 2 </script> </body> </html>
TypeError: Cannot define property prop2, object is not extensible 1 // because of freeze the value won't get delete and won't get update.