1 var obj1 = { 2 name: 'shaanxi', 3 get nameGet() { 4 return this.name + 'a'; 5 }, 6 set nameSet(name) { 7 this.name = name; 8 } 9 }; 10 11 console.info(obj1.nameGet); //shaanxia 12 obj1.nameSet = 'set by set keywords'; 13 console.info(obj1.nameGet); //set by set keywordsa
第一种方式,直接在对象内设置。如代码所示。
1 var obj2 = { 2 name: 'shaanxi' 3 }; 4 5 obj2.__defineGetter__('nameGet', function() { 6 return this.name; 7 }); 8 obj2.__defineSetter__('nameSet', function( 9 name) { 10 this.name = name; 11 }); 12 var ref1 = obj2.__lookupGetter__('nameGet'); 13 var ref2 = obj2.__lookupSetter__('nameSet'); 14 console.info(obj2.nameGet); //shaanxi 15 obj2.nameSet = 'set by __defineSetter__'; 16 console.info(obj2.nameGet); //set by __defineSetter__
第二种方式:使用原型方法进行设置
1 var obj3 = { 2 name: "shaanxi" 3 }; 4 Object.defineProperties(obj3, { 5 nameGet: { 6 value: function() { 7 return this.name; 8 } 9 }, 10 nameSet: { 11 value: function(name) { 12 this.name = name; 13 } 14 } 15 }); 16 17 console.info(obj3.nameGet()); //shaanxi 18 obj3.nameSet('set by Object.defineProperty'); 19 console.info(obj3.nameGet()); //set by Object.defineProperty
第三种方式:使用Object.defineProperty()和Object.defineProperties()进行设置