在JavaScript中,是否有方法检索函数绑定到的对象?
具体来说,我感兴趣的是如何让下面的代码工作,根据注释记录日志在JavaScript中,是否有方法检索函数绑定到的对象?,javascript,Javascript,具体来说,我感兴趣的是如何让下面的代码工作,根据注释记录日志 function someWeirdness(func) { var funcThis = undefined; // Instead of undefined, access to what, // if anything, func is bound to // (func.this doesn't work
function someWeirdness(func) {
var funcThis = undefined; // Instead of undefined, access to what,
// if anything, func is bound to
// (func.this doesn't work, but that would be
// it if it did).
console.log(funcThis);
}
function greet(greeting) {
console.log([greeting || "Hello", this.name].join(" "));
}
var obj = {
name: "object"
};
greetObj = greet.bind(obj);
someWeirdness(greetObj); // logs obj
该应用程序将更符合以下内容:
function compositionalMagic(func, params) {
params = Array.isArray(params) ?
params : Array.prototype.slice.call(arguments, 1);
// Additional processing and hooplah
func.apply(func.this, params);
}
此
仅在给定函数范围内可用-除非您有意泄漏引用
function foo( arg ) {
arg.this = this;
}
var obj = { foo: 'bar' };
var obj2 = {};
foo.call( obj, obj2 );
console.log( obj2.this ); // logs { foo: 'bar' }
您可以在每次调用bind时使用monkeypatch
Function.prototype.bind
执行上述操作,但可能并不理想。您想知道函数绑定到哪个对象,还是想记录“obj”?因为这两者之间没有关系…是的。。。对不起,伙计们。。。打字错误(或者更确切地说是brain fart将绑定的参数字符串化)。重复的,正如我在前面的内容中所解释的,如果您收到的函数的this
已绑定,并且您使用apply()
调用该函数,那么您提供的this
值将被忽略,并且将使用绑定的值。因此,如果你想遵守约束值,那么你没有问题。。。