181 this指向问题

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

现阶段,我们先了解一下几个this指向

  1. 全局作用域或者普通函数中this指向全局对象window(注意定时器里面的this指向window) 【全局作用域下的变量、函数会作为window对象的属性、方法,只是通常省略window。】

  2. 方法调用中谁调用this指向谁 【即对象中的方法指向对象自己。】
  3. 构造函数中this指向构造函数的实例。

        // 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.onclick = function() {
        //     console.log(this); // this指向的是btn这个按钮对象
        // }

        btn.addEventListener('click', function() {
            console.log(this); // this指向的是btn这个按钮对象
        })

        // 3. 构造函数中this指向构造函数的实例
        function Fun() {
            console.log(this); // this 指向的是fun 实例对象
        }
        var fun = new Fun();

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12180957.html