JavaScript classes with getter and setter cause RangeError: Maximum call stack size exceeded

前端 未结 5 463
南方客
南方客 2020-11-30 11:12

I am currently experimenting with ECMA6 classes. My current class looks like the following

class Player {
  constructor(id) {
    this.id = id;
    this.cash         


        
5条回答
  •  野性不改
    2020-11-30 11:43

    Get & Set ES6 classes brings a new syntax for getters and setters on object properties. Get and set allows us to run code on the reading or writing of a property. ES5 had getters and setters as well but was not widely used because of older IE browsers. ES5 getters and setters did not have as nice of a syntax that ES6 brings us. So lets create a get and set for our name property.

    Source: JavaScript ES6 Class Syntax

    Example:

    // ES6 get and set
    class Person {
        constructor(name) {
            this._name = name;
        }
    
        get name() {
            return this._name.toUpperCase();
        }
    
        set name(newName) {
            this._name = newName;   // validation could be checked here such as only allowing non numerical values
        }
    
        walk() {
            console.log(this._name + ' is walking.');
        }
    }
    
    let bob = new Person('Bob');
    console.log(bob.name);  // Outputs 'BOB'
    

提交回复
热议问题