最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get all objects stored inside proxy? - Stack Overflow

programmeradmin2浏览0评论

Let's assume that this is the proxy.

var target = {};
var p = new Proxy(target, {});
p.a = 1; 
p.b = 2;

I know I can access the objects via console.log(p.a) and console.log(p.b) but how do I programatically fetch all the objects stored?

Disclaimer: I'm a Javascript noob but I did read the documentation at: but it wasn't really clear.

Let's assume that this is the proxy.

var target = {};
var p = new Proxy(target, {});
p.a = 1; 
p.b = 2;

I know I can access the objects via console.log(p.a) and console.log(p.b) but how do I programatically fetch all the objects stored?

Disclaimer: I'm a Javascript noob but I did read the documentation at: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Examples but it wasn't really clear.

Share Improve this question asked May 4, 2018 at 6:42 shadyabhishadyabhi 17.3k28 gold badges85 silver badges134 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

var target = {};
var p = new Proxy(target, {});
p.a = 1; 
p.b = 2;

console.log(p);
// {
//   "a": 1,
//   "b": 2
// }

console.log(Object.keys(p));
// ["a", "b"]


// only in ES6 and above:
console.log(Object.values(p));
// [1, 2]

// In older JS versions:
for(var key of Object.keys(p)) {
  console.log(p[key]);
}
// 1
// 2

What you are looking for is the for .. in loop

for (var property in p) {
    console.log(p[property]);
}

More details here

It's a tricky question because with a Proxy object you are in plete control of what property access does. In the MDN example you're actually adding a default response for all properties - so if a property isn't found in the object, 37 is returned. In that sense, the proxied object can be said to have an infinite number of properties.

You might try Object.keys or an enumeration via for ... in, but you might not get exactly what you want if the proxy handler does a lot.

In general, when working with Proxy I'd avoid thinking about "all the properties".

You can try this also:

const example = {
Name: "What is your Name",  Age: 0 };

const Don = {
  Name : "Don Quixote",  Age: 25
};
const handler = {
  getPrototypeOf(target) {
    return Don;
  }
};
const myproxy = new Proxy(example, handler);
var a = Object.getPrototypeOf(myproxy);
for (var i in a) 
{
   console.log(i + ":" +  a[i] );
}

发布评论

评论列表(0)

  1. 暂无评论