Skip to content

Instantly share code, notes, and snippets.

@philikon
Created July 12, 2011 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philikon/1078579 to your computer and use it in GitHub Desktop.
Save philikon/1078579 to your computer and use it in GitHub Desktop.
Prebound JS methods
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript;version=1.7">
/**
* Proxy handler to automatically bind methods.
*/
function prebound(obj) {
return {
memoized: {},
get: function get(receiver, name) {
var func = obj[name];
if (!func || typeof func != "function") {
return func;
}
return this.memoized[name] || (this.memoized[name] = func.bind(receiver));
},
delete: function delete_(receiver, name) {
delete obj[name];
delete this.memoized[name];
},
set: function set(receiver, name, value) {
obj[name] = value;
delete this.memoized[name];
}
}
}
/**
* Wraps a constructor function and injects a proxy that prebinds methods.
*/
function withPreboundMethods(ctor) {
var callTrap = function(args) {}
var constructTrap = function(args) {
return Proxy.create(prebound(new ctor(args)), Object.prototype);
};
return Proxy.createFunction(ctor, callTrap, constructTrap);
}
/**
* Example
*/
function Foobar() {}
Foobar.prototype = {
method: function method() {
console.log("Are we this yet?", this == f);
}
};
Foobar = withPreboundMethods(Foobar);
var f = new Foobar();
var meth = f.method;
meth();
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment