es6 getter setter

https://stackoverflow.com/questions/34517538/setting-an-es6-class-getter-to-enumerable

 

1. 我要 getter 没有要暴露

class A { 
    get age() { 
        return 11;
    }
}

console.log(Object.keys(new A())); // []

翻译 es5

var A = /** @class */ (function () {
    function A() {
    }
    Object.defineProperty(A.prototype, "age", {
        get: function () {
            return 11;
        },
        enumerable: true,
        configurable: true
    });
    return A;
}());
console.log(Object.keys(new A())); // []

由于定义到了 prototype 上,所以 object keys 就找不到了。

 

2. 我要 getter 要暴露

class A {
    constructor() { 
        Object.defineProperty(this, 'age', {
            get: function () { 
                return 11;
            },
            enumerable: true
        })
    } 
    readonly age: number; // 为了智能提示
}

console.log(Object.keys(new A())); // ['age']

直接定义到了对象上边而不是 prototype 

 

3. 我要 getter setter 不要暴露全部

by default 是会出现 private _age 的

class A { 
    private _age: number;

    get age() { 
        return this._age;
    }
    set age(value: number) { 
        this._age = value;
    }
}
const a = new A();
a.age = 11
console.log(Object.keys(a)); // ['_age']

添加 define 

class A { 
    constructor() { 
        Object.defineProperty(this, '_age', {
            enumerable: false,
            writable: true
        });
    }
    private _age: number;

    get age() { 
        return this._age;
    }
    set age(value: number) { 
        this._age = value;
    }
}

const a = new A();
a.age = 15;
console.log(Object.keys(a));
console.log(a.age);

 

4. 我要 getter setter 暴露但不要暴露 private 

class A { 
    constructor() { 
        Object.defineProperty(this, '_age', {
            enumerable: false,
            writable: true
        });

        Object.defineProperty(this, 'age', {
            enumerable: true,
            get: function () { 
                return this._age; 
            },
            set: function (value: number) { 
                this._age = value;
            }
        });

    }
    private _age: number;
    age: number;
}

const a = new A();
a.age = 15;
console.log(Object.keys(a));
console.log(a.age);

 

转载于:https://www.cnblogs.com/keatkeat/p/10885277.html

你可能感兴趣的:(es6 getter setter)