Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript won't let me set property which only has a getter despite deleting getter

I have the following getter in one of my classes:

get password(){
        if(this._public) return null;

        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";    
        for (var i = 0; i < 10; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));   
        }

        delete this.password;
        return this.password = text;
}

There is no accompanying setter. On the line return this.password = text I get this error:

Uncaught TypeError: Cannot set property password of # which has only a getter

However, the getter should be deleted at this point, and it should have no property called password. I actually took the idea from MDN's page here (the last code snippet on the page).

Anyone know why this is happening?

Tested on Chrome 51 and Node.js (v6.0.0).

like image 708
Jonah Avatar asked Mar 12 '23 20:03

Jonah


1 Answers

As said in comments, you can't delete what isn't there. password is not a property of user, but of its prototype; so delete user.password does nothing; if you then do user.password = "foo", you will find the property user on the prototype, which is not settable.

Instead, you need to define a property on user itself:

class User {
  get password() {
    Object.defineProperty(this, "password", {
      value: "foo"
    });
    return this.password;
  }
};

var user = new User();
console.log(user.password);
like image 158
Amadan Avatar answered Apr 06 '23 21:04

Amadan