JS的getter和setter

实例对象的getter和setter

    var o = {
        _a: 11,
        _b: 22,
        get a() {
            return this._a;
        },
        set a(v) {
            this._a = v * 2;
        },
        //此处b只写,不可读
        set b(v) {
            this._b = v;
        },
        //此处c只读,不可写
        get c() {
            return Math.sqrt(this._a * this._a + this._b * this._b);
        },
        print: function() {
            console.log(this.a, this.b, this.c);
        }
    };
    o.print();
    o.a = 33;
    o.b = 44;
    o.print();
    o.c = 55; //此处更改c不起作用,也不会报错
    o.print();
    o._a = 33; //这就是恶心的地方,没有权限控制
    o.print();

输出:

11 undefined 24.596747752497688
66 undefined 79.32212806020776
66 undefined 79.32212806020776
33 undefined 55

类对象的getter和setter

    function Class() {
        //私有变量
        var a = 11,
            b = 22;
        //定义a,b,c的getter和setter,此处定义的a,b,c是公有变量
        Object.defineProperties(this, {
            a: {
                get: function() {
                    return a;
                },
                set: function(v) {
                    a = v * 2;
                }
            },
            b: { //此处b只写,不可读,读取时返回undefined
                set: function(v) {
                    b = v;
                }
            },
            c: { //此处c只读,不可写,给c赋值也不会报错
                get: function() {
                    return Math.sqrt(a * a + b * b);
                }
            }
            /*
            定义单个属性可以这样:
            Object.defineProperty(obj, "propertyName", {
                get:function(){}, set:function(v){}
            });
            */
        });
        this.print = function() {
            console.log(this.a, this.b, this.c);
        };
    }

    var o = new Class();
    o.print();
    o.a = 33;
    o.b = 44;
    o.print();
    o.c = 55;
    o.print();

输出:

11 undefined 24.596747752497688
66 undefined 79.32212806020776
66 undefined 79.32212806020776

你可能感兴趣的:(js,万物生)