Getter/setter in constructor

前端 未结 6 1279
清酒与你
清酒与你 2020-12-12 20:43

I recently read about the fact that there is a possibility of defining getters/setters in JavaScript. It seems extremely helpful - the setter is a kind of \'helper\' which c

6条回答
  •  感动是毒
    2020-12-12 21:28

    Update for ES6 -- have a look at section 19.3.1 of Alex Rauschmayer's book Exploring ES6 http://exploringjs.com/es6/ch_maps-sets.html#sec_weakmaps-private-data which demonstrates how to use WeakMaps with getters and setters to hold private data. Combining with section 16.2.2.3 http://exploringjs.com/es6/ch_classes.html#leanpub-auto-getters-and-setters would result in something like

    # module test_WeakMap_getter.js
    var _MyClassProp = new WeakMap();
    class MyClass {
        get prop() {
            return _MyClassProp.get( this ); 
        }
        set prop(value) {
            _MyClassProp.set( this, value );
        }
    }
    var mc = new MyClass();
    mc.prop = 5 ;
    console.log( 'My value is', mc.prop );
    
    $ node --use_strict test_WeakMap_getter.js 
    My value is 5
    

提交回复
热议问题