Question

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.

Était-ce utile?

La solution

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;
}

Autres conseils

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());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top