Vitaminaq / interview-collection

前端面试合集
3 stars 0 forks source link

请用两种方式实现以下功能:obj.num赋值只允许数值型 取值的时候,请以百分比形式返回 #2

Open Vitaminaq opened 2 years ago

Vitaminaq commented 2 years ago
// 方法一
const obj = {
    _num: 0
};
Object.defineProperty(obj, 'num', {
    set(val) {
        if (typeof val !== 'number') throw Error('only numbers are supported');
        this._num = val;
    },
    get() {
        return this._num * 100 + '%';
    }
});
// 方法二
const obj = new Proxy({ num: 1 }, {
    set(target, property, value) {
        if (typeof value !== 'number') throw Error('only numbers are supported');
        target[property] = value;
    },
    get(target, property) {
        return target[property] * 100 + '%';
    }
});
GetHere commented 2 years ago
//  简化了set get的写法
let obj = {
    get num(){
        return (this._num?this._num:0)+'%';
    },
    set num(val){
        if(typeof val === 'number'){
            return this._num = val;
        }
        throw Error('please input number');
    }
}