Javascript 未捕获的类型错误:无法设置 # 的属性 playerNo,它在第 4 行只有一个 getter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36553274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:13:21  来源:igfitidea点击:

Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4

javascriptecmascript-6

提问by Jonah

I'm moving from using the hacky JavaScript classes of old (functions and prototypes) to the new ES6 classes.

我正在从使用旧的(函数和原型)的 hacky JavaScript 类转移到新的 ES6 类。

I'm probably doing something stupid but I'm not sure why I'm not allowed to do this:

我可能正在做一些愚蠢的事情,但我不确定为什么我不允许这样做:

class Player{
    constructor(playerNo){
        this.playerNo = playerNo;
    }    
    get playerNo(){
        return this.playerNo;
    }

    set cards(playersCards){
        this.cards = playersCards;
    }
    get cards(){
        return this.cards;
    }
}

var steve = new Player(1);

It gives me the error: Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4

它给了我错误: Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4

So, I tried the below:

所以,我尝试了以下方法:

class Player{
    constructor(playerNo){
        this.playerNo = playerNo;
    }   
    set playerNo(no){
        this.playerNo = no;
    }
    get playerNo(){
        return this.playerNo;
    }

    set cards(playersCards){
        this.cards = playersCards;
    }
    get cards(){
        return this.cards;
    }
}

var steve = new Player(1);

Which gives me: Uncaught RangeError: Maximum call stack size exceeded on line 6(which is the line this.playerNo = no;).

这给了我:(Uncaught RangeError: Maximum call stack size exceeded on line 6这是线this.playerNo = no;)。

Any ideas?

有任何想法吗?

回答by Mark Stosberg

You have recursion with setting playerNo.

你有设置递归playerNo

In the playerNosetter, try setting this._playerNo = 0.

playerNosetter 中,尝试设置this._playerNo = 0

In the rest of the code, continue to make a distinction between the name of the setter method and the internal property that stores the data.

在剩下的代码中,继续区分 setter 方法的名称和存储数据的内部属性。