JS中this指向問題總結
阿新 • • 發佈:2018-12-17
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this</title> <style> #njn{ width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div id="njn">666</div> </body> <script> var box = document.getElementById("njn"); var obj = {}; // window和var宣告是一個效果 window.x = 9; var x = 2; // function text() { // 此時函式沒有所屬物件,所以this指得是當前window物件 // console.log(this); // console.log(this.x); // } // text(); console.log(window.x); console.log(this.x); console.log(window); // obj.x = 10; // obj.fn = function () { // //此時this代表的obj // console.log(this.x , this); // // }; // obj.fn(); // console.log(obj); // box.onclick = function () { // //此時的this指的是繫結點選是事件的標籤 // console.log(this); // console.log(this.innerHTML); // } </script> </html>