I'd like to have a property in my class that is readable, but not directly modifiable by code external to the class. Basically, equivalent of returning a const reference to member from a method in C++.
Writing something along those lines:
class test { private readonly x_ = new Uint8Array([0, 1, 2]); public x() { return this.x_;} }
does not work, because code like the following still compiles:
let a = new test(); a.x()[0] = 1;
What's the correct way of achieving this?
When a property is read-only , the property is said to be “non-writable”. It cannot be reassigned. for example you can not update or assign a value to the classList property of an element but you can read it.
Defining read-only class in Java If we make a class read-only, then we can't modify the properties or data members value of the class. If we make a class read-only, then we can only read the properties or data members value of the class.
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all.
To declare properties, add a static properties getter to the element's class. The getter should return an object containing property declarations. Attribute type, used for deserializing from an attribute. Polymer supports deserializing the following types: Boolean , Date , Number , String , Array and Object .
For future readers, We can use getter
to allow reading property outside class, but restrict edit.
class Test { private x_ = new Uint8Array([0, 1, 2]); get x() { return this.x_; } }
let test = new Test(); console.log(test.x) //Can read test.x = 1; //Error: Cannot assign to 'x' because it is a read-only property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With