Created
September 28, 2011 05:16
-
-
Save CrypticSwarm/1247044 to your computer and use it in GitHub Desktop.
Harmony Proxies experiment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//From http://wiki.ecmascript.org/doku.php?id=harmony:proxies | |
function handlerMaker(obj) { | |
return { | |
getOwnPropertyDescriptor: function(name) { | |
var desc = Object.getOwnPropertyDescriptor(obj, name); | |
// a trapping proxy's properties must always be configurable | |
if (desc !== undefined) { desc.configurable = true; } | |
return desc; | |
}, | |
getPropertyDescriptor: function(name) { | |
var desc = Object.getPropertyDescriptor(obj, name); // not in ES5 | |
// a trapping proxy's properties must always be configurable | |
if (desc !== undefined) { desc.configurable = true; } | |
return desc; | |
}, | |
getOwnPropertyNames: function() { | |
return Object.getOwnPropertyNames(obj); | |
}, | |
getPropertyNames: function() { | |
return Object.getPropertyNames(obj); // not in ES5 | |
}, | |
defineProperty: function(name, desc) { | |
Object.defineProperty(obj, name, desc); | |
}, | |
delete: function(name) { return delete obj[name]; }, | |
fix: function() { | |
if (Object.isFrozen(obj)) { | |
var result = {}; | |
Object.getOwnPropertyNames(obj).forEach(function(name) { | |
result[name] = Object.getOwnPropertyDescriptor(obj, name); | |
}); | |
return result; | |
} | |
// As long as obj is not frozen, the proxy won't allow itself to be fixed | |
return undefined; // will cause a TypeError to be thrown | |
}, | |
has: function(name) { return name in obj; }, | |
hasOwn: function(name) { return ({}).hasOwnProperty.call(obj, name); }, | |
get: function(receiver, name) { return obj[name]; }, | |
set: function(receiver, name, val) { obj[name] = val; return true; }, // bad behavior when set fails in non-strict mode | |
enumerate: function() { | |
var result = []; | |
for (var name in obj) { result.push(name); }; | |
return result; | |
}, | |
keys: function() { return Object.keys(obj); } | |
}; | |
} | |
// |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var proxy; | |
proxy = Proxy.create(handlerMaker({ a: 123, b: 45, c: { a: 'hello' } })); | |
console.log(proxy); //as expected: { a: 123, b: 45, c: { a: 'hello' } } | |
proxy = Proxy.create(handlerMaker(null)); | |
console.log(proxy); //should be null getting {} | |
proxy = Proxy.create(handlerMaker(123)); | |
console.log(proxy); //should be 123 getting {} | |
//essentially any primitive shows up as {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment