Question about ES6/2019 and objects

This isn’t really a curriculum question so I thought I’d ask it here. This is from the “Make a Person” challenge in Intermediate Algorithm Scripting.

var Person = function(firstAndLast) {
  // Only change code below this line
  // Complete the method below and implement the others similarly
  this.getFullName = function() {
    return "";
  };
  return firstAndLast;
};

var bob = new Person('Bob Ross');
bob.getFullName();

From what I understand, the point was to circumvent JavaScript’s lack of private properties by making a local variable in the function and having only the object’s properties access that local variable via closure.

My question is, how would I accomplish the same thing in ES6? So far, the curriculum hasn’t really showcased ES6’s way of declaring objects via the class keyword at all. So I’m at a bit of a loss as to how I would translate this into an ES6 object. I tried the following, but it doesn’t work.

class Person {
    constructor {
       //this.fullName = name;
       let fullName = name; //is only in scope within the constructor, and cannot be accessed by getters
    {
}

I didn’t realize it was for privacy; I thought they were just trying to make it hard and confusing. :slight_smile:

You might play around with this:

 class Pirate {
            constructor(name,motto) {
                this.name = name;
                this.motto = motto
            }
            yoho() {
                console.log("yo ho ho");
            }
            sayName() {
                console.log(this.name, this.motto);
            }
        } 
        const john = new Pirate("Long John Silver", "shiver me timbers!");

There’s a proposal for private class fields;

1 Like