Reputation: 1545
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).
Upvotes: 4
Views: 7280
Reputation: 198436
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);
Upvotes: 8