I think what you want is a weak bind:
function weakBind(functable, context) {
var GLOBAL = this;
return function () {
return functable.apply(this === GLOBAL ? context : this, arguments);
};
}
Now you can do this:
var someuser = {
name: 'George',
func: function () {
console.log(this.name);
}
};
var foo = {
name: 'foobar'
};
var func = weakBind(someuser.func, foo);
func(); // output foobar
var func2 = weakBind(func, someuser);
func2(); //output George
See the demo: http://jsfiddle.net/R79EG/
The problem with a normal bind is that once you bind an object to the this pointer it can't be overridden. The weak bind checks whether the this pointer is set to the GLOBAL object (in which case the default value is used). Otherwise it uses whatever the new this points to.
BTW in your case it's simply better to do this instead:
var someuser = {
name: 'George',
func: function () {
console.log(this.name);
}
};
var foo = {
name: 'foobar'
};
var func = someuser.func.bind(foo);
func(); // output foobar
var func2 = someuser.func.bind(someuser);
func2(); //output George
This is better than weakBind because calling func2 would call func which would in turn call someuser.func. However using bind, calling func2 would directly call someuser.func.