js对象,set和get方法 的三种实现形式

var obj1 = {
    name: 'shaanxi',
    get nameGet() {
        return this.name + 'a';
    },
    set nameSet(name) {
        this.name = name;
    }
};

console.info(obj1.nameGet); //shaanxia
obj1.nameSet = 'set by set keywords';
console.info(obj1.nameGet); //set by set keywordsa

第一种方式, 直接在对象内设置。 如代码所示。

var obj2 = {
    name: 'shaanxi'
};

obj2.__defineGetter__('nameGet', function() {
    return this.name;
});
obj2.__defineSetter__('nameSet', function(
    name) {
    this.name = name;
});
var ref1 = obj2.__lookupGetter__('nameGet');
var ref2 = obj2.__lookupSetter__('nameSet');
console.info(obj2.nameGet); //shaanxi
obj2.nameSet = 'set by __defineSetter__';
console.info(obj2.nameGet); //set by __defineSetter__

第二种方式: 使用原型方法进行设置

var obj3 = {
    name: "shaanxi"
};
Object.defineProperties(obj3, {
    nameGet: {
        value: function() {
            return this.name;
        }
    },
    nameSet: {
        value: function(name) {
            this.name = name;
        }
    }
});

console.info(obj3.nameGet()); //shaanxi
obj3.nameSet('set by Object.defineProperty');
console.info(obj3.nameGet()); //set by Object.defineProperty

第三种方式: 使用Object.defineProperty() 和Object.defineProperties() 进行设置

posted @ 2019-10-15 10:34  诗和远方-ysk  阅读(3582)  评论(0编辑  收藏  举报