Skip to content

Instantly share code, notes, and snippets.

@matt-morris
Forked from torgeir/method-missing-proxy.js
Created October 20, 2016 13:25
Show Gist options
  • Save matt-morris/7502ec8ce0256d3da970de7c4dd83d3e to your computer and use it in GitHub Desktop.
Save matt-morris/7502ec8ce0256d3da970de7c4dd83d3e 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