proxy实现Javascript私有

var api = {  
  _apiKey: '123abc456def', 
  /* mock methods that use this._apiKey */ 
  getUsers: function(){ }, 
  getUser: function(userId){ }, 
  setUser: function(userId, config){ } 
}; 
// 增加限制访问的属性在这个数组中
const RESTRICTED = ['_apiKey']; 
api = new Proxy(api, {  
    get(target, key, proxy) { 
        if(RESTRICTED.indexOf(key) > -1) { 
            throw Error(`${key} is restricted. Please see api documentation for further info.`); 
        } 
        return Reflect.get(target, key, proxy); 
    }, 
    set(target, key, value, proxy) { 
        if(RESTRICTED.indexOf(key) > -1) { 
            throw Error(`${key} is restricted. Please see api documentation for further info.`); 
        } 
        return Reflect.get(target, key, value, proxy); 
    } 
}); 
// throws an error 
console.log(api._apiKey); 

猜你喜欢

转载自blog.csdn.net/qq_40283784/article/details/86756011