JS - 객체(3)

1826 단어

get, set


속성 Getter/setter 방법
var man = {
    name: 'sunorry',
    weibo: '@sunorry',
    get age() {
        return new Date().getFullYear() - 1990;
    },
    set age(val) {
        console.log('Age can\'t be set to ' + val);
    }
};

console.log(man.age); // 25
man.age = 100; // Age can't be set to 100
console.log(man.age); // still 25

더 복잡한 예 var a = "abc"; +a;//NaN
var man = {
    weibo: '@sunorry',
    $age: null, // 
    get age() {
        if(this.$age == undefined) {
            return new Date().getFullYear() - 1990;
        } else {
            return this.$age;
        }
    },
    set age(val) {
        val = +val; //  
        if(!isNaN(val) && val > 0 && val < 150) {
            this.$age = +val;
        } else {
            throw new Error('Incorrect val = ' + val);
        }
    }
}

console.log(man.age); // 27
man.age = 100;
console.log(man.age); // 100
man.age = 'abc'; // error: Incorrect val = NaN

get/set과 원형 체인
function foo() {}

Object.defineProperty(foo.prototype, 'z', {
    get: function() {
        return 1;
    }
});

var obj = new foo();

obj.z; // 1
obj.z = 10;
obj.z; // still 1

Object.defineProperty(obj, 'z', {
    value: 100,
    configurable: true
});
obj.z; // 100;
delete obj.z;
obj.z; // back to 1
var o = {};
Object.defineProperty(o, 'x', {
    value: 1
}); // writeable=false, configurable=false
var obj = Object.create(o);
obj.x; // 1
obj.x = 200;
obj.x; // still 1, can't change it

Object.defineProperty(obj, 'x', {
    writeable: true,
    configurable: true,
    value: 100
});
obj.x; // 100
obj.x = 500;
obj.x; // 500

좋은 웹페이지 즐겨찾기