JavaScript--函数中this的几种指向

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script>
 7 //        普通函数调用
 8         function fn() {
 9             console.log("普通函数调用", this); // 输出window
10         }
11         /*
12         * window.fn = function() {}
13         * */
14         fn();
15 
16 //        构造函数调用
17         function Person() {
18             console.log("构造函数调用", this); // 输出Person对象,指向自己
19         }
20         var p1 = new Person();
21 
22 //        对象方法调用
23         var obj = {
24             sayHi:function () {
25                 console.log("对象方法调用", this); // 输出obj对象
26             }
27         };
28         obj.sayHi();
29 
30 //        事件绑定调用
31         document.onclick = function () {
32             console.log("事件绑定调用方法" , this);  // #document
33         }
34 
35 //        定时器函数调用 window.setInterval
36 //
37         setInterval(function () {
38             console.log("定时器函数调用", this); // window
39         },1000)
40 
41 
42         /*在严格模式下普通函数调用会不行出现undefined*/
43     </script>
44 </head>
45 <body>
46 
47 </body>
48 </html>

 

posted @ 2017-10-30 11:08  QinXiao.Shou  阅读(334)  评论(0编辑  收藏  举报