javascript对象定义set和get的方式解读!~

/**

     * 方式1:使用原始的set 和 get标记设置
     * @type {Object}
     */
    var obj1 = {
        name: 'shaanxi',
        get nameGet() {

            return this.name;
        },
        set nameSet(name) {
            this.name = name;
        }
    };

    console.info(obj1.nameGet);
    obj1.nameSet = 'set by set keywords';
    console.info(obj1.nameGet);
    console.info('------------------------');
    /**
     * 方式2:使用原型方法进行设置
     * @type {Object}
     */
    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);
    obj2.nameSet = 'set by __defineSetter__';
    console.info(obj2.nameGet);
    console.info('-----------------------------');
    /**
     * 使用Object.defineProperty()和Object.defineProperties()进行设置
     * @type {Object}
     */
    var obj3 = {
        name: "shaanxi"
    };

    /*Object.defineProperty(obj3, 'nameGet', {
        value: function() {
            return this.name;
        }
    });

    Object.defineProperty(obj3, 'nameSet', {
        value: function(name) {
            this.name = name;
        }
    });*/

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

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

    /**
     * end
     */

你可能感兴趣的:(javascript)