JavaScript Object-Oriented JavaScript Getters and Setters Creating Setter Methods

Buster Siem
Buster Siem
7,280 Points

If-statements conditioning to a getter-property in a setter-property?

I can't crack how I am supposed to write this if statement. I read on MDN that you had to access the level-property with the self.-prefix, but I don't think the Treehouse-teacher has taught anything about this in the video... HELP, please.

creating_setters.js
class Student {
    constructor(gpa, credits) {
        this.gpa = gpa;
        this.credits = credits;
    }

    stringGPA() {
        return this.gpa.toString();
    }

    get level() {
        if (this.credits > 90) {
            return 'Senior';
        } else if (this.credits > 60) {
            return 'Junior';
        } else if (this.credits > 30) {
            return 'Sophomore';
        } else {
            return 'Freshman';
        }
    }

    set major(major) {
      if (self.level === 'Senior' || self.level === 'Junior') {
        this._major = major;
      } else {
        this._major = 'None'
      }
    }  

}

var student = new Student(3.9, 60);

1 Answer

Steven Parker
Steven Parker
203,443 Points

Can you post a link to where you saw this? I'd be curious to see it!

But the word "self" has no special meaning in JavaScript. The appropriate prefix is "this.", just like you used for accessing the backing property.

Buster Siem
Buster Siem
7,280 Points

Thanks, Steven! I just realize now as I read the MDN page again, that I might have misunderstood it. I was also wondering why it wasn’t in the video if it was this prefix to use. Haha.