Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Read-Only Properties

I was reading this question about read-only properties, and I came upon 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 an IIFE, to also make a variable or property "private", but what I don't understand is:

Why is assignment allowed, and if it's allowed, how can nothing happen? In this snippet there is no inferred scope, so I don't understand how something in JS can infer a private property.

like image 624
Sterling Archer Avatar asked Jun 17 '15 20:06

Sterling Archer


People also ask

What is a read-only property?

A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.

What is read-only property in Javascript?

The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

What is read-only property in IOS?

Read-Only Computed PropertiesA computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but can't be set to a different value.

What is read-only property in Python?

Summary. If you need to make a read-only attribute in Python, you can turn your attribute into a property that delegates to an attribute with almost the same name, but with an underscore prefixed before the its name to note that it's private convention.


1 Answers

Why is assignment allowed, and if it's allowed, how can nothing happen? In this snippet there is no inferred scope, so I don't understand how something in JS can infer a private property.

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

If you use strict mode - you should get:

TypeError: setting a property that has only a getter

like image 189
Benjamin Gruenbaum Avatar answered Sep 21 '22 19:09

Benjamin Gruenbaum