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);
}
}
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.
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.
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.
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.
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.
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