Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use the same name for both a setter method and class property?

Tags:

typescript

In a typescript class, is there a way to use the same name for both a setter method and class property? This would make setting and getting values more consistent. For example:

myClass.myValue = "Hello"; //Setter.
var myValue = myClass.myValue; //Getter.

class myClass {
   myValue: string;

   myValue(inArg: string) {
      alert("inArg: " + inArg);
   }
}
like image 367
Lambert Avatar asked Aug 09 '16 20:08

Lambert


People also ask

Can setter and getter have same name?

If you want to use JavaScript getter/setter with the same name as the properties, e.g. to intercept certain setters to implement side effects, you can create a Proxy for your object.

What is the more pythonic way to use getters and setters?

Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.

What is the connection between encapsulation and getter and setter methods?

For the purpose of data encapsulation, most object oriented languages use getters and setters method. This is because we want to hide the attributes of a object class from other classes so that no accidental modification of the data happens by methods in other classes.

Should Python classes have getters and setters?

You don't need any getters, setters methods to access or change the attributes. You can access it directly using the name of the attributes.


1 Answers

No, and that has to do with how the class is created in javascript:

var MyClass = (function () {
    function MyClass() {
        this.myValue = "string";
    }
    MyClass.prototype.myValue = function (inArg) {
        alert("inArg: " + inArg);
    };
    return MyClass;
}());

When you then do:

let obj = new MyClass();

You create an instance of the class which has everything that exist in the prototype, including the myValue method, but then in the constructor you override the property myValue with a string.

It's similar to doing this:

class MyClass {
    myValue(inArg: string) {
      alert("inArg: " + inArg);
   }
}

let obj = new MyClass();
obj.myValue = "a string";

The only difference being that in this example you override myValue only for obj but not other instances of MyClass, whereas in your example it will do it for all instances because it's in the constructor.

like image 85
Nitzan Tomer Avatar answered Nov 11 '22 20:11

Nitzan Tomer