Javascript prototype.js中的bind()代码
我在这里看到了上面的代码: 在学习javascript时。代码摘自prototype.js。注释是由我添加的,不是来自原始代码 我的问题是为什么要使用args.concat(Array.prototype.slice.call(arguments))?我认为通过args就足够了。Javascript prototype.js中的bind()代码,javascript,prototypejs,Javascript,Prototypejs,我在这里看到了上面的代码: 在学习javascript时。代码摘自prototype.js。注释是由我添加的,不是来自原始代码 我的问题是为什么要使用args.concat(Array.prototype.slice.call(arguments))?我认为通过args就足够了。 prototype.js中的bind()必须有其有效的原因。请帮助我理解它。谢谢大家! 您还希望能够访问传递给绑定函数的参数,而不仅仅是绑定到函数的参数 args指传递给.bind的参数,arguments指传递给绑定
prototype.js中的bind()必须有其有效的原因。请帮助我理解它。谢谢大家! 您还希望能够访问传递给绑定函数的参数,而不仅仅是绑定到函数的参数
args
指传递给.bind
的参数,arguments
指传递给绑定函数的参数(由.bind
返回的参数)
对.bind
进行更改,并使用以下功能比较版本:
Function.prototype.bind = function(){
var fn = this,
// clone arguments
args = Array.prototype.slice.call(arguments),
// get the first argument, which should be an object, and args will be modified.
object = args.shift();
return function(){
return fn.apply(object,
// why use concat??? why?
args.concat(Array.prototype.slice.call(arguments)));
};
};
...
elem.onclick = Button.click.bind(Button, false);
....
使用args.concat(Array.prototype.slice.call(arguments))代码>,输出将为
function foo() {
console.log(arguments);
}
var bound = foo.bind(null, 1, 2);
bound(3, 4);
仅使用args
,它将
[1, 2, 3, 4]
对于事件处理程序,如果只使用args
谢谢,您将无法访问传递给它的事件对象!你的最后一句话对我帮助很大。
[1, 2]