在 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?
我还是个新手,抱歉搞混了。
谢谢!