Skip to content

Instantly share code, notes, and snippets.

@torgeir
Last active May 17, 2024 03:40
Show Gist options
  • Save torgeir/e528337e7a9a41c96ac9 to your computer and use it in GitHub Desktop.
Save torgeir/e528337e7a9a41c96ac9 to your computer and use it in GitHub Desktop.
es6 proxies method missing example
/*
What happens?
- `new Type().what` is looked up with a call to `get` on the proxy
- a function is returned that will look up `METHOD_NAME` when called
- `METHOD_NAME` is called because of the `()` behind `new Type().what`
- if `METHOD_NAME` exists on you object, your own function is called
- if not, because of prototypal inheritance, `get` is called again
- `name` is now `METHOD_NAME` and we can throw as we know `METHOD_NAME` is not implemented on the type
credits http://soft.vub.ac.be/~tvcutsem/proxies/
*/
var MethodMissingTrap = (function () {
var METHOD_NAME = "methodMissing";
return Proxy.create({
get: function (o, name) {
if (name === METHOD_NAME) {
throw new Error("A missing method was called, but your object does not implement '." + METHOD_NAME + "(name, args)'.");
}
else {
return function () {
var args = [].slice.call(arguments);
return this[METHOD_NAME](name, args);
};
}
},
getPropertyDescriptor: function (o, name) {
return { value: o[name], writable: true, enumerable: true, configurable: true };
}
});
})();
// example
function Type () { }
Type.prototype = Object.create(MethodMissingTrap);
Type.prototype.methodMissing = function (name, args) {
console.log("That wasn't so smart, now, was it?", name, args);
};
new Type().what(1, 2, 3); // That wasn't so smart, now, was it? what [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment