Created
July 12, 2011 18:15
-
-
Save philikon/1078579 to your computer and use it in GitHub Desktop.
Prebound JS methods
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
<!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