ES6:几种get和set的使用

ES6:几种get和set的使用

一、基于普通对象的实现

const demo = {
          
   
    _name = ;
    
    get name(){
          
   
        return this._name;
    }
	set name(val){
          
   
        this._name = val;
    }
}

demo.name = yivi;
console.log(demo.name);		// yivi

二、基于class的实现

class Demo{
          
   
    constructor(){
          
   
        this._name = ;
    }
    
    get name(){
          
   
        return this._name;
    }
    
    set name(val){
          
   
        this._name = val;
    }
}

const demo = new Demo();
demo.name = yivi;
console.log(demo.name);		// yivi

三、基于Object.defineProperty的实现

const demo = {
          
   
    _name : 
}

Object.defineProperty(demo,name,{
          
   
    get: function(){
          
   
        return this._name;
    },
    
    set: function(val){
          
   
		this._name = val;	
	}
})

demo.name = yivi;
console.log(demo.name);		// yivi

四、基于Proxy对象的实现

const demo = {
          
   
    _name : 
}

const proxy = new Proxy(demo,{
          
   
    get: function(target,proName){
          
   
        return proName === name? target[_name] : undefined;
    },
    
    set: function(target,proName){
          
   
    	proName === name && (target[_name] = val)	
	}
})

demo.name = yivi;
console.log(demo.name);		// yivi

五、基于__defineGetter__和__defineSetter__的实现(现废弃)

const demo = {
          
   
    _name : 
}

demo.__defineGetter__(name,function(){
          
   
    return this._name;
})

demo.__defineSetter__(name,function(val){
          
   
    this._name = val;
})

demo.name = yivi;
console.log(demo.name);		// yivi

六、五种方式的区别

    前两种的getter和setter都只能在定义的时候实现,后三种方式可以动态地设置属性。 当不需要动态添加属性时,推荐用class的方式来定义getter和setter; 当需要动态添加属性时,推荐用proxy的方式来定义;
经验分享 程序员 微信小程序 职场和发展