Reputation: 610
I've been using the keyword get and set of JavaScript but I don't think that I'm implementing it correctly.
_maxWinnings: -1,
get maxWinnings() {
return this._maxWinnings;
},
setMaxWinnings : function( value ) {
this._maxWinnings = value;
// This works fine.
// this.maxWinnings = value;
}
I've done series of tests and the results are not as expected.
console.log( this.sgd._maxWinnings );
> -1
console.log( this.sgd.maxWinnings );
> -1
console.log( this.sgd.setMaxWinnings(10) );
> undefined
console.log( this.sgd._maxWinnings );
> 10
console.log( this.sgd.maxWinnings );
> -1
I hope that you could help me out.
Upvotes: 0
Views: 87
Reputation: 569
The get and set keywords don't work that way.
function SGD()
{
this._maxWinnings = 0;
return this;
}
Object.defineProperty(SGD, 'maxWinnings', {
get : function () { return this._maxWinnings; },
set : function (val) { this._maxWinnings = val; }
});
var sgd = new SGD();
sgd.maxWinnings = 100;
alert(sgd.maxWinnings.toString());
Upvotes: 1
Reputation: 664630
setMaxWinnings : function( value ) { // This works fine: // this.maxWinnings = value; }
No, it doesn't. You've written a setter method that you need to call (like sgd.setMaxWinnings(10))
, but if you want a property assignment setter then you will need to use
set maxWinnings( value ) {
this._maxWinnings = value;
}
Upvotes: 3