this關鍵字表示對象
例: 1.方法中的this
1 <p id="demo"></p>
2 <script>
3 // 創(chuàng)建一個對象
4 var person = {
5 firstName: "John",
6 lastName : "Doe",
7 id : 5566,
8 fullName : function() {
9 return this.firstName + " " + this.lastName;
10 }
11 };
12
13 // 顯示對象的數(shù)據(jù)
14 document.getElementById("demo").innerHTML = person.fullName();
實例中,this 指向了 person 對象,因為 person 對象是 fullName 方法的所有者。 輸出:John Doe 2.單獨使用this 1 <p id="demo"></p>
2 <script>
3 var x = this;
4 document.getElementById("demo").innerHTML = x;
5 </script>
單獨使用 this,則它指向全局(Global)對象。 在瀏覽器中,window 就是該全局對象為 [object Window]: 3.函數(shù)中使用this(默認)1 <p id="demo"></p>
2 <script>
3 document.getElementById("demo").innerHTML = myFunction();
4 function myFunction() {
5 return this;
6 }
7 </script>
在函數(shù)中,函數(shù)的所屬者默認綁定到 this 上。 在瀏覽器中,window 就是該全局對象為 [object Window]。 嚴格模式下: 1 <p id="demo"></p>
2 <script>
3 "use strict";
4 document.getElementById("demo").innerHTML = myFunction();
5 function myFunction() {
6 return this;
7 }
8 </script>
函數(shù)中,默認情況下,this 指向全局對象。 嚴格模式下,this 為 undefined,因為嚴格模式下不允許默認綁定:undefined 4.事件中的this1 <body>
2 <button onclick="this.style.display='none'">點我后我就消失了</button>
3 </body>
在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。 5.對象方法中的this 1 <body>
2 <p id="demo"></p>
3 <script>
4 // 創(chuàng)建一個對象
5 var person = {
6 firstName : "John",
7 lastName : "Doe",
8 id : 5566,
9 myFunction : function() {
10 return this;
11 }
12 };
13 // 顯示表單數(shù)據(jù)
14 document.getElementById("demo").innerHTML = person.myFunction();
15 </script>
16 </body>
在實例中,this 指向了 fullName 方法所屬的對象 person。 輸出:[object Object] 6.顯示函數(shù)綁定 1 <body>
2 <p id="demo"></p>
3 <script>
4 var person1 = {
5 fullName: function() {
6 return this.firstName + " " + this.lastName;
7 }
8 }
9 var person2 = {
10 firstName:"John",
11 lastName: "Doe",
12 }
13 var x = person1.fullName.call(person2);
14 document.getElementById("demo").innerHTML = x;
15 </script>
16 </body>
在 JavaScript 中函數(shù)也是對象,對象則有方法,apply 和 call 就是函數(shù)對象的方法。這兩個方法異常強大,他們允許切換函數(shù)執(zhí)行的上下文環(huán)境(context),即 this 綁定的對象。當我們使用 person2 作為參數(shù)來調用 person1.fullName 方法時, this 將指向 person2, 即便它是 person1 的方法。 輸出:John Doe |
|
|