[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze [Back]  [Original]

Object.freeze() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Object.freeze()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

Object.freeze() : , , , . , . .

In this article

Object.freeze(obj)

obj

.

, . , , TypeError ( , , ).

- . - ( ) ( , ). , , , , .

js
var obj = {
  prop: function () {},
  foo: "bar",
};

//    ,      
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;

//   ,      .
//       .
var o = Object.freeze(obj);

o === obj; // true
Object.isFrozen(obj); // === true;

//       
obj.foo = "quux"; //    
obj.quaxxor = "the friendly duck"; //    

// ...         TypeError
function fail() {
  "use strict";
  obj.foo = "sparky"; //  TypeError
  delete obj.quaxxor; //  TypeError
  obj.sparky = "arf"; //  TypeError
}

fail();

//      Object.defineProperty   
Object.defineProperty(obj, "ohai", { value: 17 }); //  TypeError
Object.defineProperty(obj, "foo", { value: "eit" }); //  TypeError

, - ( ).

js
obj = {
  internal: {},
};

Object.freeze(obj);
obj.internal.a = "A";

obj.internal.a; // 'A'

//    obj  ,      obj.
//     .
function deepFreeze(obj) {
  //      obj
  var propNames = Object.getOwnPropertyNames(obj);

  //      
  propNames.forEach(function (name) {
    var prop = obj[name];

    //   prop,   
    if (typeof prop == "object" && prop !== null) deepFreeze(prop);
  });

  //    obj (  ,    )
  return Object.freeze(obj);
}

obj2 = {
  internal: {},
};

deepFreeze(obj2);
obj2.internal.a = "";
obj2.internal.a; // undefined

ES5 ( ), TypeError. ES2015 , .

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

> Object.freeze(1)
1                             //  ES2015

Specification
ECMAScript 2027 LanguageSpecification
# sec-object.freeze


Web Proxy Viewer  |  New URL  |  Original Page