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

Object.freeze() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Object.freeze()

Baseline

20157

Object.freeze() freeze()

JavaScript

const obj = {
  prop: 42,
};

Object.freeze(obj);

obj.prop = 33;
// 

console.log(obj.prop);
// : 42

js
Object.freeze(obj)

obj

configurable false writable false TypeError

writable configurable false

freeze()

TypedArray DataView TypeError

js
Object.freeze(new Uint8Array(0)); // 
// Uint8Array []

Object.freeze(new Uint8Array(1)); // 
// TypeError: 

Object.freeze(new DataView(new ArrayBuffer(32))); // 
// DataView {}

Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)); // 
// Float64Array []

Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)); // 
// TypeError: 

3 (buf.byteLength, buf.byteOffset, buf.buffer) ArrayBuffer SharedArrayBuffer

Object.seal() Object.freeze()

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

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

// 
const 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.foo; // TypeError 
  delete obj.quaxxor; //  'quaxxor'  true 
  obj.sparky = "arf"; // TypeError 
}

fail();

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

// 
//  TypeError 
Object.setPrototypeOf(obj, { x: 20 });
obj.__proto__ = { x: 20 };

js
const a = [0];
Object.freeze(a); // 

a[0] = 1; // 

//  TypeError 
function fail() {
  "use strict";
  a[0] = 1;
}

fail();

// push 
a.push(2); // TypeError 

js
const obj1 = {
  internal: {},
};

Object.freeze(obj1);
obj1.internal.a = "value";

obj1.internal.a; // 'value'

Object.freeze(object) object object

js
const employee = {
  name: "Mayank",
  designation: "Developer",
  address: {
    street: "Rohini",
    city: "Delhi",
  },
};

Object.freeze(employee);

employee.name = "Dummy"; // 
employee.address.city = "Noida"; // 

console.log(employee.address.city); // : "Noida"

function prototype

deepFreeze() deepFreeze() WeakSet window

js
function deepFreeze(object) {
  // 
  const propNames = Reflect.ownKeys(object);

  // 
  for (const name of propNames) {
    const value = object[name];

    if ((value && typeof value === "object") || typeof value === "function") {
      deepFreeze(value);
    }
  }

  return Object.freeze(object);
}

const obj2 = {
  internal: {
    a: null,
  },
};

deepFreeze(obj2);

obj2.internal.a = "anotherValue"; // 
obj2.internal.a; // null

ECMAScript 2027 LanguageSpecification
# sec-object.freeze


Web Proxy Viewer  |  New URL  |  Original Page