zoukankan      html  css  js  c++  java
  • 244 函数内部的this指向:6种

    这些 this 的指向,是当我们调用函数的时候确定的。调用方式的不同决定了this 的指向不同。
    一般指向我们的调用者。


    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <button>点击</button>
        <script>
            // 函数的不同调用方式决定了this 的指向不同
            // 1. 普通函数 this 指向window
            function fn() {
                // 普通函数的this指向:[object Window]
                console.log('普通函数的this指向:' + this);
            }
            window.fn();
    
    
            // 2. 对象的方法 this指向的是对象 o
            var o = {
                sayHi: function() {
                    // 对象方法的this指向:[object Object]
                    console.log('对象方法的this指向:' + this);
                }
            }
            o.sayHi();
    
    
            // 3. 构造函数 this 指向 ldh 这个实例对象 原型对象里面的this 指向的也是 ldh这个实例对象
            function Star() {
                this.dancing = function() {
                    // 构造函数的this指向:[object Object]
                    console.log('构造函数的this指向:' + this);
                }
            };
            Star.prototype.sing = function() {
                // 构造函数的原型对象的this指向:[object Object]
                console.log('构造函数的原型对象的this指向:' + this);
            }
            var ldh = new Star();
            ldh.dancing();
            ldh.sing();
    
    
            // 4. 绑定事件函数 this 指向的是函数的调用者 btn这个按钮对象
            var btn = document.querySelector('button');
            btn.onclick = function() {
                // 绑定时间函数的this指向:[object HTMLButtonElement]
                console.log('绑定时间函数的this指向:' + this);
            };
    
    
            // 5. 定时器函数 this 指向的也是window
            window.setTimeout(function() {
                // 定时器的this指向:[object Window]
                console.log('定时器的this指向:' + this);
            }, 1000);
    
    
            // 6. 立即执行函数 this还是指向window
            (function() {
                // 立即执行函数的this指向:[object Window]
                console.log('立即执行函数的this指向:' + this);
            })();
        </script>
    </body>
    
    </html>
    
  • 相关阅读:
    前端知识 | 一个简单的登录页面包含多少前端基础知识?
    SQLserver查询作业、视图、函数、存储过程中的关键字
    SQL server 数据库备份至服务器本地磁盘和其他服务器磁盘
    Linux(centos)安装vim
    CentOS6 7 8更换阿里yum源
    centos8 最小化安装 无 ifconfig,netstat 的安装
    修改MySQL用户的host属性
    阿里云NTP服务器(国内可用的NTP服务器)
    vCenter Server Appliance(VCSA )7.0 部署指南
    Chrome离线安装包最新版
  • 原文地址:https://www.cnblogs.com/jianjie/p/12229344.html
Copyright © 2011-2022 走看看