Object.freeze() 方法 freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

Object.freeze(obj)
					

参数

obj

The object to freeze.

返回值

The object that was passed to the function.

描述

Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a TypeError exception (most commonly, but not exclusively, when in 严格模式 ).

For data properties of a frozen object, values cannot be changed, the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.

freeze() returns the same object that was passed into the function. It does not create a frozen copy.

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError . In ES2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned.

> Object.freeze(1)
TypeError: 1 is not an object // ES5 code
> Object.freeze(1)
1                             // ES2015 code
					

An ArrayBufferView with elements will cause a TypeError , as they are views over memory and will definitely cause other possible issues:

> Object.freeze(new Uint8Array(0)) // No elements
Uint8Array []
> Object.freeze(new Uint8Array(1)) // Has elements
TypeError: Cannot freeze array buffer views with elements
> Object.freeze(new DataView(new ArrayBuffer(32))) // No elements
DataView {}
> Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements
Float64Array []
> Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements
TypeError: Cannot freeze array buffer views with elements
					

Note that; as the standard three properties ( buf.byteLength , buf.byteOffset and buf.buffer ) are read-only (as are those of an ArrayBuffer or SharedArrayBuffer ), there is no reason for attempting to freeze these properties.

Comparison to Object.seal()

Objects sealed with Object.seal() can have their existing properties changed. Existing properties in objects frozen with Object.freeze() are made immutable.

范例

Freezing objects

var obj = {
  prop: function() {},
  foo: 'bar'
};
// Before freezing: new properties may be added,
// and existing properties may be changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
// Freeze.
var o = Object.freeze(obj);
// The return value is just the same object we passed in.
o === obj; // true
// The object has become frozen.
Object.isFrozen(obj); // === true
// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';
// In strict mode such attempts will throw TypeErrors
function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws a TypeError
  delete obj.foo; // throws a TypeError
  delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added
  obj.sparky = 'arf'; // throws a TypeError
}
fail();
// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });
// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }
					

Freezing arrays

let a = [0];
Object.freeze(a); // The array cannot be modified now.
a[0] = 1; // fails silently
// In strict mode such attempt will throw a TypeError
function fail() {
  "use strict"
  a[0] = 1;
}
fail();
// Attempted to push
a.push(2); // throws a TypeError
					

The object being frozen is immutable . However, it is not necessarily constant . The following example shows that a frozen object is not constant (freeze is shallow).

obj1 = {
  internal: {}
};
Object.freeze(obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'
					

To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. The object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.

What is "shallow freeze"?

The result of calling Object.freeze( object ) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object . If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.

var employee = {
  name: "Mayank",
  designation: "Developer",
  address: {
    street: "Rohini",
    city: "Delhi"
  }
};
Object.freeze(employee);
employee.name = "Dummy"; // fails silently in non-strict mode
employee.address.city = "Noida"; // attributes of child object can be modified
console.log(employee.address.city) // Output: "Noida"
					

To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered. An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling deepFreeze() recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as [window].

function deepFreeze(object) {
  // Retrieve the property names defined on object
  var propNames = Object.getOwnPropertyNames(object);
  // Freeze properties before freezing self
  for (let name of propNames) {
    let value = object[name];
    if(value && typeof value === "object") {
      deepFreeze(value);
    }
  }
  return Object.freeze(object);
}
var obj2 = {
  internal: {
    a: null
  }
};
deepFreeze(obj2);
obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode
obj2.internal.a; // null
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Object.freeze' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
freeze Chrome 6 Edge 12 Firefox 4 IE 9 Opera 12 Safari 5.1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 12 Safari iOS 6 Samsung Internet Android 1.0 nodejs Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: