Hacker News new | ask | show | jobs
by Lerc 2712 days ago
I tend to agree with the article author about the use of a # (or indeed any punctuation mark) for private fields. I think it is just a personal preference thing though. Is there any publicly available discussion that shows what lead to this decision?

If fields in class definitions are incorporated I would like it to simultaneously make the field names in scope for any methods within the class definition.

  class Fish extends Vertebrate {
    color = "blue";
    constructor (speed) {
      super();
      this.speed = speed;  
      if (speed > 5) color = "red" // does not need this.color because color is a class field.
    }
  }

  Fish.prototype.setColor = function (newValue) {
     this.color = newValue;  // this. is required because this function is outside the class definition.
  }
Adding this feature would allow for much tidier method bodies since there is now enough information to imply this.fieldName from fieldName alone.
1 comments

Ok reading that I'm going to amend my suggestion above.

    class fish {
     color = "blue";     // color is now a name in scope for this class definition
     #agenda = "Total World Domination"  // agenda is now a name in scope for this class definition

    ...
     reveal () {
       console.log("I am a " 
               + color + " Fish "  // interpreted as this.color
               +"seeking " + agenda // interpreted as this.#agenda;
     }
    }

You can still have this.agenda for public addon fields. But for the private one you can refer to it within the class definition without either this. or #
Yes please make the syntax simple like this! Even cleaner:

  class fish {
     color = "blue";    
     private agenda = "World Peace"  
     constructor(){
           color="red"
           agenda="Secret World Domination"
     }
     reveal () {
       console.log(`I am a ${color} Fish seeking ${agenda}`)
     }
    }