`

How to bind a method to an object from angularjs source code

 
阅读更多
function bind(self, fn) {  
  var slice = [].slice;  
  var curryArgs = arguments.length > 2  
    ? slice.call(arguments, 2, arguments.length)  
    : [];  
  if (typeof fn == "function" && !(fn instanceof RegExp)) {  
    return curryArgs.length  
      ? function() {  
          return arguments.length  
            ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0, arguments.length)))  
            : fn.apply(self, curryArgs);  
        }  
      : function() {  
          return arguments.length  
            ? fn.apply(self, arguments)  
            : fn.call(self);  
        };  
  } else {  
    // in IE, native methods are not functions and so they can not be bound (but they don't need to be)  
    return fn;  
  }  
}  
  
function Foo(name){  
this.name= name;  
}  
  
var print = function (prefix){  
console.log(prefix+this.name);  
}  
  
var cat = new Foo("cat");  
  
var printCat = bind(cat, print, "I am a ");  //printCat will always be bound to cat from now on.
printCat(); // I am a cat 

function zoo(printCat){
  printCat();
}

zoo(printCat);// where ever we use the function printCat, it is bound to cat
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics