我知道它在函数内部this
。
var func = function {
return this.f === arguments.callee;
// => true, if bound to some object
// => false, if is bound to null, because this.f === undefined
}
var f = func; // not bound to anything;
var obj = {};
obj1.f = func; // bound to obj1 if called as obj1.f(), but not bound if called as func()
var bound = f.bind(obj2) // bound to obj2 if called as obj2.f() or as bound()
编辑:
你实际上不能调用obj2.f()
as f
doesn't become a property ofobj2
编辑结束。
问题是:如何在这个函数之外找到函数绑定的对象?
我想实现这一点:
function g(f) {
if (typeof(f) !== 'function') throw 'error: f should be function';
if (f.boundto() === obj)
// this code will run if g(obj1.f) was called
doSomething(f);
// ....
if (f.boundto() === obj2)
// this code will run if g(obj2.f) or g(bound) was called
doSomethingElse(f);
}
和部分应用而不更改函数绑定到的对象:
function partial(f) {
return f.bind(f.boundto(), arguments.slice(1));
}
共识:
你不能这样做。外卖:使用bind
并this
非常小心:)