1. 程式人生 > >JS基礎_this補充

JS基礎_this補充

變量 code -s ext ava body ctype span class

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <script type="text/javascript">
 7             
 8             //創建一個name變量
 9             var name = "全局";
10             
11             //
創建一個fun()函數 12 function fun(){ 13 console.log(this.name); 14 } 15 16 //創建兩個對象 17 var obj = { 18 name:"孫悟空", 19 sayName:fun 20 }; 21 22 var
obj2 = { 23 name:"沙和尚", 24 sayName:fun 25 }; 26 27 //-------------------------------------------------------------------------------------- 28 //我們希望調用obj.sayName()時可以輸出obj的名字 29 30 obj.sayName();
//孫悟空 31 32 obj2.sayName();//沙和尚 33 34 35 36 </script> 37 </head> 38 <body> 39 </body> 40 </html>

JS基礎_this補充