Javascript setter和getter返回不同的输出 [英] Javascript setter and getter return different outputs
本文介绍了Javascript setter和getter返回不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在使用关键字get和set的JavaScript,但我认为我没有正确实现它.
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
我希望你能帮助我.
推荐答案
setMaxWinnings : function( value ) {
// This works fine:
// this.maxWinnings = value;
}
不,不是.您已经编写了一个需要调用的setter方法(例如sgd.setMaxWinnings(10))
,但如果要使用属性分配setter,则需要使用
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;
}
这篇关于Javascript setter和getter返回不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文