/**
* 方式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
*/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。