Js获取和设置对象中属性的两种方法分析

158 阅读1分钟

第一种:

使用对象中的方法(包含函数的属性)

var obj={
	counter:0,
	reset:function(){
		return this.counter=1;
	},
	increment:function(){
		return this.counter++;
	},
	decrement:function(){
		return this.counter--;
	},
	add:function(value){
		return this.counter+=value;
	},
	subtract:function(value){
		return this.counter-=value;
	}
}
document.write(obj.reset()+"<br/>");     //1
document.write(obj.increment()+"<br/>"); //1
document.write(obj.decrement()+"<br/>"); //2
document.write(obj.add(2)+"<br/>");      //3
document.write(obj.subtract(4));         //-1

显然直接使用方法不要太简单,也很直观。

第二种:

使用ES5中的getset关键字,是一种对象访问器

var obj = {
  counter : 0,
  get reset() {
    return this.counter = 0;
  },
  get increment() {
    return this.counter++;
  },
  get decrement() {
   return this.counter--;
  },
  set add(value) {
    this.counter += value;
  },
  set subtract(value) {
    this.counter -= value;
  }
};
document.write(obj.reset+'<br/>');        //0
document.write(obj.increment+"<br/>");    //0
document.write(obj.decrement+"<br/>");    //1
obj.add=2;
document.write(obj.counter+"<br/>");     //2
obj.subtract=3
document.write(obj.counter);            //-1

1)这里要注意的是get是获取属性值的意思,想直接返回值必须要加return,否则返回的是未定义。

2)还有set是表示要设置属性值,你不能直接write(obj.add(2));因为set addvalue)不是一个函数,必须要先修改对象属性值,在返回对象属性值,不是直接返回,一步到位。

区别

可以看到用对象方法相对于使用关键字可以直接调用一步到位

用关键字比较简介明了,JavaScript 可以确保更好的数据质量

一个是使用函数形式访问,一个是属性形式访问