Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A property that is read-only outside of the class, but read-write for class members

Tags:

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?

like image 507
nicebyte Avatar asked Nov 17 '16 08:11

nicebyte


People also ask

What does read-only property mean?

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.

What is a read-only property in Java?

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.

How do you declare a property in a classroom?

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.

How do you declare a property?

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 .


1 Answers

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. 
like image 145
Sameer Avatar answered Oct 05 '22 04:10

Sameer