Created
February 15, 2012 13:04
-
-
Save 1999/1835570 to your computer and use it in GitHub Desktop.
Proxy API implementation example
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
/** | |
* Proxy API implementation example | |
* @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy | |
*/ | |
let proxyHandlerMaker = function(obj) { | |
return { | |
// Fundamental traps | |
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)) { | |
return Object.getOwnPropertyNames(obj).map(function(name) { | |
return Object.getOwnPropertyDescriptor(obj, name); | |
}); | |
} | |
// 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 | |
}, | |
// derived traps | |
has: function(name) { return name in obj; }, | |
hasOwn: function(name) { return Object.prototype.hasOwnProperty.call(obj, name); }, | |
get: function(receiver, name) { | |
if (name == "schemeIs") { | |
return function(aScheme) { | |
aScheme = aScheme.toLowerCase(); | |
return (aScheme == obj.scheme) || (aScheme == "chrome" && /\.dtd$/.test(obj.spec)); | |
}; | |
} | |
return obj[name]; | |
}, | |
set: function(receiver, name, val) { | |
obj[name] = val; | |
return true; | |
}, | |
enumerate: function() { | |
let result = []; | |
for (name in obj) { | |
result.push(name); | |
}; | |
return result; | |
}, | |
keys: function() { return Object.keys(obj); } | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment