JavaScript之bind,call,apply
参考:
- http://rangercyh.blog.51cto.com/1444712/1615809
function foo(a,b) { this.x = this.x + a + b; } //case 1: var obj = {x:3}; foo.apply(obj,[1,2]); //obj <==> {x:6} //case 2: var obj = {x:3}; foo.call(obj, 1, 2); //obj <==> {x:6} //case 3: var obj = {x:3}; var foo1 = foo.bind(obj, 1, 2); foo1(); //obj <==> {x:6}
区别:
call与apply的区别在于apply中传给foo的参数统一放到第二个参数数组中,call从第二个参数起皆为传给foo的参数;
call与bind的区别,call将立刻执行,bind返回一个新函数;