我知道它在函数内部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()
Edited:
你实际上不能打电话obj2.f()
as 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
and this
非常小心:)
部分申请
您可以进行部分应用:
// This lets us call the slice method as a function
// on an array-like object.
var slice = Function.prototype.call.bind(Array.prototype.slice);
function partial(f/*, ...args */) {
if (typeof f != 'function')
throw new TypeError('Function expected');
var args = slice(arguments, 1);
return function(/* ...moreArgs */) {
return f.apply(this, args.concat(slice(arguments)));
};
}
该函数绑定到什么对象?
此外,对于你的问题的第一部分有一个非常直接的解决方案。不确定这是否适合您,但您可以很容易地在 JS 中进行猴子修补。猴子补丁bind
是完全有可能的。
var _bind = Function.prototype.apply.bind(Function.prototype.bind);
Object.defineProperty(Function.prototype, 'bind', {
value: function(obj) {
var boundFunction = _bind(this, arguments);
boundFunction.boundObject = obj;
return boundFunction;
}
});
只需在任何其他脚本运行之前运行它,以及任何使用的脚本bind
,它会自动添加一个boundObject
函数的属性:
function f() { }
var o = { };
var g = f.bind(o);
g.boundObject === o; // true
(注意:我假设您处于上述 ES5 环境中,因为您正在使用bind
.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)