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>
    
  • 相关阅读:
    c#基础语法(第二节课后作业/笔记)
    C#第四节课
    Hello, cnblog!
    64位的系统可以让IIS在32位的环境下运行asp.net程序(转)
    Web.Config中设置Session问题,导致无法向会话状态服务器发出会话状态请求
    远程测试asp.net web service 配置
    jQuery不使用$方法
    导入数据到SQL SERVER 2005方法
    图片与Base64相互转换,c#与java通用
    一道递归算法题,一道冒泡算法题
  • 原文地址:https://www.cnblogs.com/jianjie/p/12229344.html
Copyright © 2011-2022 走看看