bind()函数的作用

bind()函数是Function原型上的一个属性,当某个函数调用此方法时,可以通过向bind()函数传入执行对象和调用bind的函数的参数来改变函数的执行对象

1 /*问题:改变func执行环境,使之输出1*/
2 var User = {
3     count: 1,
4     getCount: function() {
5         return this.count;
6     }
7 };
8 var func = User.getCount.bind(User);
9 func();

IE6,7,8的兼容bind()函数

1 Function.prototype.bind = Function.prototype.bind || function(context) {
2     var self=this;
3     var args=Array.prototype.slice.call(arguments,1);
4     return function(){
5         return self.apply(context,args);
6     };
7 };
1 /*自定义函数*/
2 function bind(fn,context){
3     var args=Array.prototype.slice.call(arguments,2);
4     return function(){
5         var innerArgs=Array.prototype.slice.call(arguments);
6         var finalArgs=args.concat(innerArgs);
7         return fn.apply(context,finalArgs);
8     };
9 }
原文地址:https://www.cnblogs.com/Iona/p/4745412.html