【发布时间】:2013-01-13 19:28:16
【问题描述】:
我知道函数内部是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(),因为f 不会成为obj2 的属性
编辑结束。
问题是:如何在这个函数之外找到函数绑定的对象?
我想实现这个:
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要非常小心:)
【问题讨论】:
-
除非函数是使用
.bind()创建的,否则函数不会绑定到任何东西。它们可以被对象引用,但没有对象绑定。 -
我强烈怀疑答案是你不能这样做。
-
@h2ooooooo boundto() 是一种假设的方法,它不存在。让其他人认为不可能的代码更有效率有什么意义? :) 开个玩笑……
-
函数是独立的实体。
this所指的内容是在调用它们时确定的(即在运行时)。但是,如果f已经使用.bind绑定,那么再次调用.bind无论如何都不会改变this。 -
另请参阅stackoverflow.com/q/7282158/471129,以讨论从绑定结果中获取原始函数的可能性,这是获取
this的另一只鞋。 (答案是你不能,至少使用标准绑定。)
标签: javascript function functional-programming this ecmascript-5