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

第一种方式,直接在对象内设置。如代码所示。
    var obj1 = {
        name: 'Rich',
        get nameGet() {
            return this.name + 'a';
        },
        set nameSet(name) {
            this.name = name;
        }
    };

    console.info(obj1.nameGet);  //Rich
    obj1.nameSet = 'set by set keywords';
    console.info(obj1.nameGet);  //set by set keywords
第二种方式:使用原型方法进行设置
    var obj2 = {
        name: 'Rich'
    };

    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);  //Rich
    obj2.nameSet = 'set by __defineSetter__';
    console.info(obj2.nameGet);  //set by __defineSetter__
第三种方式:使用Object.defineProperty()和Object.defineProperties()进行设置
    var obj3 = {
        name: "Rich"
    };
     Object.defineProperties(obj3, {
        nameGet: {
            value: function() {
                return this.name;
            }
        },
        nameSet: {
            value: function(name) {
                this.name = name;
            }
        }
    });

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

你可能感兴趣的:(js对象,set和get方法 的三种实现形式)