美文网首页
JS中函数内的this指向问题

JS中函数内的this指向问题

作者: 每日log | 来源:发表于2020-12-22 15:08 被阅读0次

    函数中的this指向通常是根据谁调用了该函数决定的

    01、普通函数

    普通函数中的this指向window。

    function fn() {
        console.log(this); //[object Window]
    }
    fn();
    

    02、立即执行函数

    立即执行函数中的this指向window。

    (function() {
        console.log(this);// [object Window]
    })();
    

    03、对象里的函数

    对象的方法中的this指向的是对象obj。

    var obj = {
        test: function() {
            console.log(this);// [object Object]
        }
    }
    obj.test();
    

    04、构造函数

    构造函数中的 this以及构造函数原型对象里的this都指向new出来的 person实例对象。

    function Person() {
        console.log(this)
    };
    Person.prototype.sing = function() {
        console.log(this)
    }
    var person = new Person();
    

    05、事件绑定函数

    事件绑定里的this根据调用该函数的对象决定‍。

    btn.onclick = function() {
        console.log(this); // btn对象
    };
    

    06、定时器函数

    定时器函数里的this指向的是window。

    window.setTimeout(function() {
        console.log('定时器的this:' + this);// [object Window]
    }, 1000);
    

    07、箭头函数

    箭头函数不绑定this,如果箭头函数中使用this ,this关键字将指向箭头函数定义位置中的this。

    function fn () {
      console.log(this); // {name: 'zhangsan'}
      return () => {
        console.log(this) // {name: 'zhangsan'}
      }
    }
    const o = {name: 'zhangsan'};
    const fnResult = fn.call(o);
    fnResult();
    

    fn 使用call方法改变this的指向,此时fn中的this指向的是o这个对象。
    在fn中return一个箭头函数,箭头函数如果使用this,是根据函数定义位置决定的,此时箭头函数定义在fn中,那么箭头函数this也指向o。

    下一篇:JS中改变函数内部this的指向问题

    相关文章

      网友评论

          本文标题:JS中函数内的this指向问题

          本文链接:https://www.haomeiwen.com/subject/lujsnktx.html