原创转载请注明出处:http://agilestyle.iteye.com/blog/2341901
Preventing Object Modification
When you want to lock down an object’s properties in some way, there are three different ways to do so.
Preventing Extensions
If you use Object.preventExtensions(), objects will no longer allow properties to be added.
var person1 = { name: "Nicholas" }; console.log(Object.isExtensible(person1)); // true Object.preventExtensions(person1); console.log(Object.isExtensible(person1)); // false person1.sayName = function () { console.log(this.name); }; console.log("sayName" in person1); // false
Sealing Objects
You could also create a sealed object with the Object.seal() method, which makes that object non-extensible and makes its properties nonconfigurable.
var person1 = { name: "Nicholas" }; console.log(Object.isExtensible(person1)); // true console.log(Object.isSealed(person1)); // false Object.seal(person1); console.log(Object.isExtensible(person1)); // false console.log(Object.isSealed(person1)); // true person1.sayName = function() { console.log(this.name); }; console.log("sayName" in person1); // false person1.name = "Greg"; console.log(person1.name); // "Greg" delete person1.name; console.log("name" in person1); // true console.log(person1.name); // "Greg" var descriptor = Object.getOwnPropertyDescriptor(person1, "name"); console.log(descriptor.configurable); // false
Freezing Objects
The Object.freeze() method creates a frozen object, which is a sealed object with nonwritable data properties.
var person1 = { name: "Nicholas" }; console.log(Object.isExtensible(person1)); // true console.log(Object.isSealed(person1)); // false console.log(Object.isFrozen(person1)); // false Object.freeze(person1); console.log(Object.isExtensible(person1)); // false console.log(Object.isSealed(person1)); // true console.log(Object.isFrozen(person1)); // true person1.sayName = function() { console.log(this.name); }; console.log("sayName" in person1); // false person1.name = "Greg"; console.log(person1.name); // "Nicholas" delete person1.name; console.log("name" in person1); // true console.log(person1.name); // "Nicholas" var descriptor = Object.getOwnPropertyDescriptor(person1, "name"); console.log(descriptor.configurable); // false console.log(descriptor.writable); // false
Be careful with nonextensible objects, and always use strict mode so that attempts to access the objects incorrectly will throw an error.
Reference
Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014