JSON stringify ES6 class property with getter/setter

后端 未结 5 1800
一向
一向 2020-11-30 13:40

I have a JavaScript ES6 class that has a property set with set and accessed with get functions. It is also a constructor parameter so the class can

5条回答
  •  Happy的楠姐
    2020-11-30 14:15

    Use private fields for internal use.

    class PrivateClassFieldTest {
        #property;
        constructor(value) {
            this.property = value;
        }
        get property() {
            return this.#property;
        }
        set property(value) {
            this.#property = value;
        }
    }
    

    class Test {
    	constructor(value) {
    		this.property = value;
    	}
    	get property() {
    		return this._property;
    	}
    	set property(value) {
    		this._property = value;
    	}
    }
    
    class PublicClassFieldTest {
    	_property;
    	constructor(value) {
    		this.property = value;
    	}
    	get property() {
    		return this.property;
    	}
    	set property(value) {
    		this._property = value;
    	}
    }
    
    class PrivateClassFieldTest {
    	#property;
    	constructor(value) {
    		this.property = value;
    	}
    	get property() {
    		return this.#property;
    	}
    	set property(value) {
    		this.#property = value;
    	}
    }
    
    console.log(JSON.stringify(new Test("test")));
    console.log(JSON.stringify(new PublicClassFieldTest("test")));
    console.log(JSON.stringify(new PrivateClassFieldTest("test")));

提交回复
热议问题