zoukankan      html  css  js  c++  java
  • this指向问题

    this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,一般情况下this的最终指向的是那个调用它的对象。

    我们了解一下几个this指向:

    1. 全局作用域或者普通函数中this指向全局对象window(注意定时器里面的this指向window)

    2. 方法调用中谁调用this指向谁

    3. 构造函数中this指向构造函数的实例

     <button>点击</button>
        <script>
            // this 指向问题 一般情况下this的最终指向的是那个调用它的对象
            // 1. 全局作用域或者普通函数中this指向全局对象window( 注意定时器里面的this指向window)
            console.log(this);
            function fn() {
                console.log(this);
            }
            window.fn();
            window.setTimeout(function() {
                console.log(this);
            }, 1000);
            // 2. 方法调用中谁调用this指向谁
            var o = {
                sayHi: function() {
                    console.log(this); // this指向的是 o 这个对象
                }
            }
            o.sayHi();
            var btn = document.querySelector('button');
            btn.addEventListener('click', function() {
                    console.log(this); // 事件处理函数中的this指向的是btn这个按钮对象
                })
            // 3. 构造函数中this指向构造函数的实例
            function Fun() {
                console.log(this); // this 指向的是fun 实例对象
            }
            var fun = new Fun();
        </script>
    

      

  • 相关阅读:
    HDU2546(01背包)
    HDU4283(KB22-G)
    POJ1651(KB-E)
    POJ2955(KB22-C 区间DP)
    POJ3264(KB7-G RMQ)
    POJ3468(KB7-C 线段树)
    POJ3616(KB12-R dp)
    Ubuntu16.04安装opencv for python/c++
    华中农业大学第五届程序设计大赛网络同步赛-L
    华中农业大学第五届程序设计大赛网络同步赛-K
  • 原文地址:https://www.cnblogs.com/clarehjh/p/14800035.html
Copyright © 2011-2022 走看看