Câu hỏi phỏng vấn Javascript
Câu hỏi

How to deep-freeze o...

Câu trả lời

To deep-freeze an object in JavaScript means to recursively apply Object.freeze() to an object and all objects it references, directly or indirectly, so that the entire structure becomes immutable. This is necessary because Object.freeze() is shallow and only freezes the object's immediate properties. If the object has properties that are objects themselves, these nested objects can still be modified unless they are also frozen.

Here's a function that demonstrates how to deep-freeze an object in JavaScript:

javascript Copy
function deepFreeze(object) {
  // Retrieve the property names defined on object
  const propNames = Object.getOwnPropertyNames(object);

  // Freeze properties before freezing self
  for (const name of propNames) {
    const value = object[name];

    // If value is an object and not already frozen, recursively call deepFreeze
    if (value && typeof value === 'object' && !Object.isFrozen(value)) {
      deepFreeze(value);
    }
  }

  // Freeze self (no-op if already frozen)
  return Object.freeze(object);
}

To use this function, you would call it with the object you want to freeze:

javascript Copy
const myObject = {
  internal: {
    a: null
  }
};

deepFreeze(myObject);

// Now myObject is deeply frozen, and attempts to modify it will throw errors (in strict mode)
myObject.internal.a = 'someValue'; // TypeError: Cannot assign to read only property 'a' of object '#<Object>'

This function works by first freezing the properties of the object, which might themselves be objects, and then freezing the object itself. It uses Object.getOwnPropertyNames() to find all properties (including non-enumerable ones) and then recursively applies Object.freeze() to each property that is an object. Finally, it freezes the original ob...

expert

expert

Gợi ý câu hỏi phỏng vấn

expert

Is JavaScript a pass-by-reference or pass-by-value language?

expert

What is the difference between the await keyword and the yield keyword?

senior

What is the new keyword in JavaScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào