7

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);
   }
}
Lambert
  • 2,233
  • 5
  • 29
  • 44

1 Answers1

6

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.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Ok, I had seen this work in other libraries. They must not be written in javascript. – Lambert Aug 10 '16 at 15:09
  • Here is a javascript library where it works: https://developers.arcgis.com/javascript/ – Lambert Aug 11 '16 at 13:56
  • And where do they do what you say? In their samples? Or library code? if so where is it? – Nitzan Tomer Aug 11 '16 at 13:59
  • In the documentation for the library, samples, etc. It works for the entire API. – Lambert Aug 11 '16 at 14:03
  • I can't see in their example code anything close to what you described. Where do they have a function and a member with the same name? – Nitzan Tomer Aug 11 '16 at 14:16
  • https://developers.arcgis.com/javascript/latest/guide/working-with-props/index.html – Lambert Aug 11 '16 at 14:20
  • I'm sorry, I still don't see anything like that there. Unless you are referring to something like this: `var map = new Map({ basemap: 'streets' });` and then `map.basemap = "topo";` ? – Nitzan Tomer Aug 11 '16 at 14:24