JavaScript中的this详解

this关键字表示对象

  • 在方法中,this表示该方法所属的对象;
  • 如果单独使用,this表示全局对象;
  • 在函数中,this表示全局对象;
  • 在函数中,在严格模式下,this是未定义的(undefined);
  • 在事件中,this表示接受事件的元素;
  • 类似call( )apply( )方法可以将this引用到任何对象。

例:

1.方法中的this

 

 1 <p id="demo"></p>
 2 <script>
 3     // 创建一个对象
 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     // 显示对象的数据
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.函数中使用this(默认)

1 <p id="demo"></p>
2 <script>
3     document.getElementById("demo").innerHTML = myFunction();
4     function myFunction() {
5         return this;
6     }
7 </script>

在函数中,函数的所属者默认绑定到 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>

函数中,默认情况下,this 指向全局对象。

严格模式下,this undefined,因为严格模式下不允许默认绑定:undefined

4.事件中的this

1 <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     // 创建一个对象
 5     var person = {
 6         firstName  : "John",
 7         lastName   : "Doe",
 8         id     : 5566,
 9         myFunction : function() {
10             return this;
11         }
12     };
13     // 显示表单数据
14     document.getElementById("demo").innerHTML = person.myFunction();
15 </script>
16 </body>

在实例中,this 指向了 fullName 方法所属的对象 person

输出:[object Object]

6.显示函数绑定

 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 中函数也是对象,对象则有方法,apply call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法。

输出:John Doe

posted @ 2020-08-28 14:09  叹叹  阅读(476)  评论(0编辑  收藏  举报