javascript小知识1 this的用法
函数的应用:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script> 9 function f(){ 10 alert(this.x); 11 } 12 var x = 1; 13 var a = { 14 x :2 15 } 16 a.f2 = f; 17 var cc = a.f2() 18 console.log(cc) 19 </script> 20 </body> 21 </html>
你猜 cc 是多少,是2;
再看一个例子:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script> 9 10 var x = 1; 11 var a = { 12 x: 2, 13 fn: function() { 14 return (this.x) 15 } 16 } 17 var b = { 18 x: 3 19 } 20 q = a.fn(); 21 p = a.fn; 22 q1 = p(); 23 b.f2 = a.fn; 24 q3 = b.f2(); 25 q5 = (b.f2)(); 26 d = b.f2; 27 q4 = d(); 28 console.log("q" + "~~~~" + q) 29 console.log("q1" + "~~~~" + q1) 30 console.log("q3" + "~~~~" + q3) 31 console.log("q4" + "~~~~" + q4) 32 console.log("q5" + "~~~~" + q5) 33 </script> 34 </body> 35 </html>
注意q3与q5这俩结果是一样的;
坚持下去就能成功