Read-only object properties

I was reading this question about read -only properties and I came to this snippet:

var myObject = {
    get readOnlyProperty() { return 42; }
};

alert(myObject.readOnlyProperty); // 42
myObject.readOnlyProperty = 5;    // Assignment is allowed, but doesn't do anything
alert(myObject.readOnlyProperty); // 42

      

Now, I know to hide the scope you can use IIFE to make the variable or property "private" as well, but I don't understand:

Why is assignment allowed, and if it is allowed, how can nothing happen? This snippet is missing a valid scope, so I don't understand how something in JS can infer private property.

+3


source to share


2 answers


Why is assignment allowed, and if it is allowed, how can nothing happen? This snippet is missing a valid scope, so I don't understand how something in JS can infer private property.

Since assignments (prior to strict mode) never throw and do it throw, this would violate the invariant people expect. While you can still override it (by creating a setter and making this cast), this is the default behavior in JavaScript for properties. We don't like it, but this is what it is.



If you are using strict mode, you should get:

TypeError: setting a property that only has a getter

+6


source


Getters and setters in object literals express pure sugar over Object.defineProperty()

as used in ES5.

What a getter does is that it returns a specific value when a property of a specific object is requested.

let obj = {};
obj.foo = 3; // I am SETTING a property value
obj.foo; // I am GETTING the property value

      

So whenever you define getter

, every time you ask for a property, you get the return value getter

.

So if you have



let obj = {};

Object.defineProperty(obj, 'readOnly', {
    'get': function() { return 42; }
});

      

or

let obj = {
    get readOnly() { return 42; }
};

      

Your variable will always be 42 because it can only return that value. You can try setting this property to any value, but it will always return 42 in the end.

You can add the installer to the forbidden destination and make it throw Error

+2


source







All Articles