严格模式和非严格模式下的this指向问题

一、全局环境

1.函数调用

非严格模式:this指向是Window

// 普通函数
function fn () {
      console.log(this, 'this');
    }
    fn()

// 自执行函数
 (function fn () {
      console.log(this, 'this');
    })()

严格模式:this指向是undefined 

// 开启严格模式
  'use strict'
    function fn () {
      console.log(this, 'this');
    }
    fn()


// 自执行函数
 (function fn () {
      console.log(this, 'this');
    })()

 二、对象方法中的this

对象方法中的this,无论是严格模式还是非严格模式,谁调用就是谁,对象调用就是对象

 'use strict'
    const obj = {
      id: 1,
      newFn: function () {
        console.log(this, 'obj-this');
      }
    }

    obj.newFn()

三、定时器中的this

定时器中的this,无论是严格模式还是非严格模式,this指向是Window

'use strict';
    setTimeout(function () {
      console.log(this, 'this');
    }, 0);

 

总结:对于JS代码中没有写执行主体的情况下,非严格模式默认都是window执行的,所以this指向的是window,但是在严格模式下,没有写执行主体,this指向是undefined

猜你喜欢

转载自blog.csdn.net/weixin_48082900/article/details/129288536
今日推荐