zoukankan      html  css  js  c++  java
  • Day2-JS-this 关键字

    JavaScript this 关键字

    一、对象中的this

    var person = {
      firstName: "John",
      lastName : "Doe",
      id     : 5566,
      fullName : function() {
        return this.firstName + " " + this.lastName;
      }
    };

    二、单独使用 this

    <script>
    var x = this;
    document.getElementById("demo").innerHTML = x;
    </script>

    这个得到的结果就是:[object Window]

    ===直击单独的使用this ,this 指向了 window 对象

    三、事件中的 this

    <button onclick="this.style.display='none'">点我后我就消失了</button>

    这个this表示的就是这个标签button了,

    四、显式函数绑定

    在 JavaScript 中函数也是对象,对象则有方法,apply 和 call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。

    在下面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法

    ①知识点:

        1、即使是调用了person1这个对象里面的函数,但是后面加了call(person2)也就把this转变为指向person2了

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h2>JavaScript this 关键字</h2>
    <p>实例中 <strong>this</strong> 指向了 person2,即便它是 person1 的方法:</p>
    
    <p id="demo"></p>
    
    <script>
        var person1={
            fullName:function(){
                return this.firstName+" "+this.lastName;
            }
        }
        var person2={
            firstName:"c",
            lastName:"j"
        }
        var x=person1.fullName.call(person2);
        document.getElementById("demo").innerHTML = x; 
    </script>
    </body>
    </html>
    View Code

    归纳:

    this 的多种指向:

    •  1、在对象方法中, this 指向调用它所在方法的对象。
    •  2、单独使用 this,它指向全局(Global)对象。
    •  3、函数使用中,this 指向函数的所属者。
    •  4、严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
    •  5、在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。
    •  6、apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象
  • 相关阅读:
    day 01
    day14
    day12
    day13
    day11
    day9
    day10
    day08
    day07
    day06
  • 原文地址:https://www.cnblogs.com/SCAU-gogocj/p/13111020.html
Copyright © 2011-2022 走看看