1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>借用方法/ 绑定</title> 6 <style type="text/css"> 7 #wrap{width:100px;height:200px;background: #000;} 8 </style> 9 </head> 10 <body> 11 <div id="wrap"></div> 12 <script type="text/javascript"> 13 var wrap = document.getElementById("wrap"); 14 15 //例子1: 借用数组方法 16 function f(){ 17 console.log(typeof arguments); //object 18 var args = [].slice.call(arguments,1,3); 19 console.log(args); 20 } 21 22 //f(1,2,3,4,5,6); //[2, 3] 23 24 25 // call() / apply() 26 //one 27 var one = { 28 name : "object", 29 say : function(greet){ 30 return greet + "," + this.name; 31 } 32 }; 33 console.log(one.say('hi')); //hi,object 34 35 //two 36 var two = { 37 name : "another object" 38 }; 39 console.log(one.say.apply(two, ["Hello"])); //Hello,another object 40 41 //给变量赋值,'this' 将指向全局变量 42 var say = one.say; 43 console.log(say("hoho")); //hoho,undefined 44 45 //作为回调函数传递, 'this' 也指向 window 46 var yetanother = { 47 name : "Yet another object", 48 method : function(callback){ 49 var _this = this; 50 wrap.onclick = function(){ 51 console.log(_this); // <div id="wrap"></div> // 注意this的指向 借用_this 继续指向object 否则是指向那个div 52 }; 53 return callback("Hola"); 54 } 55 }; 56 var a = yetanother.method(one.say); 57 console.log(a); //Hola,uedefined 58 59 60 61 function bind(o, m){ 62 return function(){ 63 return m.apply(o, [].slice.call(arguments)); 64 } 65 } 66 67 </script> 68 </body> 69 </html>