在Javascript中,如何在不绑定this参数的情况下将参数绑定到函数?
例如:
//Example function.
var c = function(a, b, c, callback) {};
//Bind values 1, 2, and 3 to a, b, and c, leave callback unbound.
var b = c.bind(null, 1, 2, 3); //How can I do this without binding scope?
如何避免必须绑定函数范围的副作用(例如,设置this= null)?
编辑:
对困惑感到抱歉。我想绑定参数,然后能够稍后调用绑定函数,并使它的行为就像我调用原始函数并将其传递给绑定参数一样:
var x = 'outside object';
var obj = {
x: 'inside object',
c: function(a, b, c, callback) {
console.log(this.x);
}
};
var b = obj.c.bind(null, 1, 2, 3);
//These should both have exact same output.
obj.c(1, 2, 3, function(){});
b(function(){});
//The following works, but I was hoping there was a better way:
var b = obj.c.bind(obj, 1, 2, 3); //Anyway to make it work without typing obj twice?
我对此仍然很陌生,很抱歉造成混乱。
谢谢!
bind()be 的第一个值为什么会有问题null?似乎在FF中工作正常。
this完全不绑定JavaScript。它总是意味着什么。因此,绑定this到this封闭函数很有意义。
this吗?var b = c.bind(this, 1,2,3);