JavaScript Basics: Object.preventExtensions and Object.isExtensible

in #javascript7 years ago

In JavaScript, an object is extensible by default. This means that new properties can be added to the object. In some circumstances, you my want to prevent extensions to the object. To this end, you can use Object.preventExtensions. This function prevents any extensions to the object, so that no new property can be added to the object. If you try to add new properties to the object, it will cause a TypeError (or fail silently if not in strict mode).

Here is an example:

    let myObj = {
        name: "Ali",
    };
    Object.isExtensible(myObj); // true
    Object.preventExtensions(myObj);
    Object.isExtensible(myObj); // false
    myObj.age = 19; // fails silently
    myObj.age; // undefined

It should be noted that after making an object inextensible, its __proto__ property becomes immutable. In other words, you cannot assign a new value to the __proto__ property. However, if the prototype is extensible, you can add new properties to the prototype.

As the EcmaScript standard attempts to organize the global objects, this functions are also available on the Reflect global object. So you can use Reflect.isExtensible and Reflect.preventExtensions instead.


Related Posts

Sort:  

interesting article ,, EcmaScript ! I didn't know about EcmaScript before ! can u please tell us to know what’s the difference between JavaScript and ECMAScript?? I mean in another post...actually if u have time ... regards !

Thank you. There is no difference. ECMAScript is the name of the ECMA-262 standard for the JavaScript language.

really ! thanks for the info

Great information abaout javascript....thanka for sharing..keep it up

so informative post for me. thanks for your post.

For a long time I wanted to learn JavaScript. But the schedule of the office and training was not the same at the same time. Your posts have a lot of work for me. Thanks @ghasemkiani for sharing the wonderful posts.

Bisyar khub...

Information is useful

Its great information JavaScript very good calculate but very difficult to understand . But nice lacture sir @ghasemkiani and thanks for sharing with us.
Stay blessed.
Steem on!

love to read it... thanks for sharing

Upvote done mr: @ghasemkiani

This really require more tutorial because we are in the era of technology

Javascript is onviously one of the best languages ever invented in computer world..like it