通常来讲,默认状况下,对象都是可拓展的,咱们能够为其属性进行增删改等操做,也能够更改他们原型的指向,如何让一个对象变得不可拓展呢,咱们能够使用ES5提供的几个方法,来保证锁定的对象是不可拓展的javascript
Object.preventExtensionsjava
Object.preventExtensions能够锁定对象,设置对象的不可拓展,能够阻止为对象添加新的属性,非严格模式下会默默不起做用,可是严格模式下会报错,能够用Object.isExtensible判断对象是否可拓展code
var person = { name: "cala" }; Object.preventExtensions(person); person.name = "John"; person.age = 24; // 严格模式下会报错: TypeError: Cannot add property age, object is not extensible console.log(person) // {name: "John"}
Object.seal对象
Object.seal和上面的Object.preventExtensions方法做用是同样,字面意思是密封,也是用来防止对象被拓展,另外还能够阻止对象已有属性和方法的删除,能够用Object.isSealed判断对象是否可拓展ip
var person = { name: "cala" }; Object.seal(person); console.log(Object.isExtensible(person)); // false console.log(Object.isSealed(person)); // true delete person.name // 删除属性失败 严格模式下 Uncaught TypeError: Cannot delete property 'name' of #<Object> person.age = 30; // // 严格模式下会报错: TypeError: Cannot add property age, object is not extensible console.log(person) // {name: "cala"}
Object.freeze原型
做用与上述两个方法大体相同,字面意思是冰冻,还能够阻止对象的属性和方法被修改,能够用Object.isFrozen判断对象是否可拓展io
var person = { name: "cala" }; Object.freeze(person); console.log(Object.isExtensible(person)); // false console.log(Object.isSealed(person)); // true console.log(Object.isFrozen(person)); // true person.name = "xyz"; person.age = 30; delete person.name //上述三个操做,非严格模式不起做用,严格模式会报错 console.log(person) // {name: "cala"}
总的来讲,上述三个操做方法preventExtensions,seal,freeze能够设置对象的不可拓展性,而且每一个方法都针对对象的不可拓展有着不一样的限制,另外还有三个判断方法,isExtensible,isSealed,isFrozen来对对象进行操做,返回Boolean值,来判断对象是否可拓展console