Javascript setter and getter return different outputs

隐身守侯 提交于 2019-12-25 07:15:52

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/23515188/javascript-setter-and-getter-return-different-outputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!