具体来说,我对如何使下面的代码工作感兴趣,根据评论记录。
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);
}
答案 0 :(得分:0)
this
仅在给定的函数范围内可用 - 除非您故意泄漏引用。
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
执行类似上面的操作,但可能并不理想。