1// Copyright JS Foundation and other contributors, http://js.foundation 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15var obj = { 16 prop: function() {}, 17 foo: 'bar' 18}; 19// New properties may be added, existing properties may be changed or removed. 20obj.foo = 'baz'; 21obj.lumpy = 'woof'; 22delete obj.prop; 23 24var o = Object.seal(obj); 25 26assert (o === obj); 27assert (Object.isSealed (obj) === true); 28 29// Changing property values on a sealed object still works. 30obj.foo = 'quux'; 31assert (obj.foo === 'quux'); 32// But you can't convert data properties to accessors, or vice versa. 33try { 34 Object.defineProperty(obj, 'foo', { get: function() { return 42; } }); // throws a TypeError 35 assert (false); 36} catch (e) { 37 assert (e instanceof TypeError); 38} 39 40// Now any changes, other than to property values, will fail. 41obj.quaxxor = 'the friendly duck'; // silently doesn't add the property 42delete obj.foo; // silently doesn't delete the property 43 44assert (obj.quaxxor === undefined); 45assert (obj.foo === 'quux') 46 47try { 48 // Attempted additions through Object.defineProperty will also throw. 49 Object.defineProperty (obj, 'ohai', { value: 17 }); // throws a TypeError 50 assert (false); 51} catch (e) { 52 assert (e instanceof TypeError); 53} 54 55try { 56 Object.defineProperties (obj, { 'ohai' : { value: 17 } }); 57 assert (false); 58} catch (e) { 59 assert (e instanceof TypeError); 60} 61 62Object.defineProperty (obj, 'foo', { value: 'eit' }); 63assert (obj.foo === 'eit') 64 65// Objects aren't sealed by default. 66var empty = {}; 67assert (Object.isSealed (empty) === false); 68 69// If you make an empty object non-extensible, it is vacuously sealed. 70Object.preventExtensions (empty); 71assert (Object.isSealed (empty) === true); 72 73// The same is not true of a non-empty object, unless its properties are all non-configurable. 74var hasProp = { fee: 'fie foe fum' }; 75Object.preventExtensions (hasProp); 76assert (Object.isSealed (hasProp) === false); 77 78// But make them all non-configurable and the object becomes sealed. 79Object.defineProperty (hasProp, 'fee', { configurable: false }); 80assert (Object.isSealed (hasProp) === true); 81 82// The easiest way to seal an object, of course, is Object.seal. 83var sealed = {}; 84Object.seal (sealed); 85assert (Object.isSealed (sealed) === true); 86