Skip to content

Instantly share code, notes, and snippets.

@DavidBruant
Created October 19, 2012 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBruant/3918227 to your computer and use it in GitHub Desktop.
Save DavidBruant/3918227 to your computer and use it in GitHub Desktop.
ProxyMap. Maybe what objects should have been?
"use strict";
(function(global){
var handler = new Proxy({
get: function(target, name){
return target.get(name);
},
set: function(target, name, value){
target.set(name, value);
return true;
},
delete: function(target, name){
return target.delete(name)
},
has: function(target, name){
return target.has(name)
}
},
/*throwingMetaHandler*/ {
get: function(target, trap){
var op = target[trap];
if(typeof op !== 'function')
throw new Error('The trap '+trap+' cannot be used')
else
return target[trap];
}
});
global.ProxyMap = function ProxyMap(){
return new Proxy(new Map(), handler);
}
})(this);
@DavidBruant
Copy link
Author

So basically, it's a wrapper around maps to make them look like objects. It's just syntactic sugar.
The interesting part is that it's an object with all the ES5 property descriptor details removed.

@DavidBruant
Copy link
Author

The meta-handler trick is here because I'm lazy to make all unwritten traps throw :-)

@rauschma
Copy link

Suggestions:

  • There seems to be a closing parenthesis missing (line 29, instead of the curly brace.

  • Show a few examples of ProxyMap in use.

  • I’d set it up like this:

    var ProxyMap = function () {
        ...
        return function () { ... };
    }();
    

@rwaldron
Copy link

"use strict"; outside of IIFE? :(

@DavidBruant
Copy link
Author

Thanks for your comments. Weird at didn't get the notifications at the time...
@rwldrn what's the problem with the "use strict" outside the IIFE?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment