zoukankan      html  css  js  c++  java
  • javascript——this关键字

    JavaScript中的this关键字

      javascript中的this关键字指的是它所属的对象,它拥有不同的值,具体取决于它所在的位置。

      在方法中,this指的是该方法所有者对象

      在单独的情况下,this指的是全局对象。

      在函数中,this指的是全局对象

      在函数中,如果是严格模式,this指的是undefined

      在事件中,this指的是接收事件的元素

    方法中的this:

    <!DOCTYPE html>
    <html>
    
    <body>
        <h1>方法中的this</h1>
        <p>本例中,this是指person对像</p>
        <p id="demo"></p>
    </body>
    
    <script>
        //创建一个对象
        var person = {
            firstName: "Bill",
            lastName: "Get",
            id: 678,
            fullName: function() {
           //this指的是拥有该fullName方法的person对象
    return this.firstName + " " + this.lastName; } }; //显示数据 document.getElementById("demo").innerHTML = person.fullName(); </script> </html>

    单独的this(在严格模式下,单独的this也是指代全局对象window)

    <!DOCTYPE html>
    <html>
    
    <body>
        <h1>单独的this</h1>
        <p>在本例中,this指的是window对象</p>
        <p id="demo" style="color: bisque;"></p>
    </body>
    
    <script>
        //this指的是全局对象
        var x = this;
        //输出全局对象
        document.getElementById("demo").innerHTML = this.x;
    </script>
    
    </html>

          

    函数中的this:(在严格模式下是undefined)

      函数中的this指的是全局对象,因为函数是属于全局对象的

    <!DOCTYPE html>
    <html>
    
    <body>
        <h1>函数中的this</h1>
        <p id="demo"></p>
    </body>
    <script>
        document.getElementById("demo").innerHTML = myFunction();
    
        function myFunction() {
            return this;
        }
    </script>
    
    </html>

     事件中的this:

    <!DOCTYPE html>
    <html>
    
    <head>
        <title>事件中的this</title>
    </head>
    
    <body>
        <h1>
            事件中的this
        </h1>
        <button onclick="this.style.display='none'">点击来删除</button>
    </body>
    
    </html>
  • 相关阅读:
    laravel常用函数大全Helper
    laravel查询语句指定索引(mysql强制索引)
    laravel-admin后台系统开发
    ES搜索引擎详解
    怎么查看当前的git分支是基于哪个分支创建的
    laravel中使用offsetSet
    laragon安装新的php版本
    Laravel collect妙用
    composer install file could not be downloaded (HTTP/1.1 405 Not Allowed)
    garphql
  • 原文地址:https://www.cnblogs.com/zhilili/p/12787552.html
Copyright © 2011-2022 走看看