This points to the problem in strict mode and non-strict mode

1. Global environment

1. Function call

Non-strict mode: this points to Window

// Ordinary
function function fn () {       console.log(this, 'this');     }     fn()


// self-executing function
 (function fn () {       console.log(this, 'this');     })()

Strict mode: this points to undefined 

// Enable strict mode
  'use strict'
    function fn () {       console.log(this, 'this');     }     fn()



// self-executing function
 (function fn () {       console.log(this, 'this');     })()

 

 Two, this in the object method

The this in the object method, whether it is strict mode or non-strict mode, whoever calls it, and the object call is the object

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

    obj.newFn()

 

3. this in the timer

This in the timer, whether it is strict mode or non-strict mode, this points to Window

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

 

Summary: For the case where the execution body is not written in the JS code, the non-strict mode is executed by the window by default, so this points to the window, but in the strict mode, the execution body is not written, and the this point is undefined

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/129288536