Sales1 min read120 words

How to use Object.freeze() in JavaScript?

Erkan Sivas

PlusClouds Author

Cloud & SaaS

How to use Object.freeze() in JavaScript?
Size

الكائنات والمصفوفات في JavaScript قابلة للتغيير. هذا يعني أنه يمكننا تغيير كائن (أو مصفوفة) في أي وقت نريده. ولكن إذا لم نرغب في حدوث ذلك لأي سبب ونريد جعل الكائن غير قابل للتغيير.


يمكننا القيام بذلك باستخدام طريقة freeze().


الكائن الذي تقوم بتجميده باستخدام طريقة freeze() لا يمكن تغييره بعد الآن؛ تجميد كائن باستخدام freeze يمنع إضافة خصائص جديدة، إزالة الخصائص الموجودة، تغيير القابلية للتعداد، القابلية للتكوين، أو القابلية للكتابة للخصائص الموجودة، وتغيير قيم الخصائص الموجودة. بالإضافة إلى ذلك، تجميد كائن يمنع أيضًا تعديل النموذج الأولي.


يمكنني إضافة مثال على الكود لاستخدام هذه الطريقة:
const obj = {
    name: "Jack"
};

Object.freeze(obj);

obj.name = "Kelly";
// Throws an error in strict mode

console.log(obj.name);
// expected output: "Jack"



ليدوشن

هل فريق المبيعات يلاحق العملاء المحتملين الخطأ؟

1.8B+ شركات — البحث دائمًا مجاني

اعثر على جهات الاتصال الخاصة بي →

No credit card · Cancel anytime

#There is no text provided for translation. Please provide the text you would like to be translated into English.

الأسئلة الشائعة

What does Object.freeze do in JavaScript and what parts of an object does it affect?

Object.freeze makes an object immutable by preventing adding new properties, removing existing properties, or changing the enumerability, configurability, or writability of existing properties, and by preventing changes to their values. It also prevents the object's prototype from being modified.

Can I still read property values from a frozen object?

Yes. After freezing, you can still read property values; for example, obj.name would print 'Jack'.

What happens if I try to change a property on a frozen object?

You cannot change a frozen object's properties; attempting to assign a new value will throw an error in strict mode.

Does freezing an object also prevent modifying its prototype?

Yes. Freezing an object also prevents the prototype from being modified.

How do I freeze an object in code?

Use Object.freeze on the object, for example: const obj = { name: 'Jack' }; Object.freeze(obj); After freezing, attempts to change properties will throw an error in strict mode.

What happens to existing properties after freezing?

Freezing prevents changing the values of existing properties. It also prevents changing the enumerability, configurability, or writability of those properties.