Why is this variable used in the function?

  • 0
    DD, help me plz !, though I don't understand why var self = this is used, as well as this is generally assigned, I read that it is used to use the main context of the function in nested functions, but for some reason in a simple example
    function a() {
        let self = this; // widnow
        console.log(this); 
        var fn = function () {
          console.log(this); //widnow
          console.log(self); // function a
        };
        fn();
      }
      a();

    but it turns out that all console.log references the window object
    JavaScript Kira Bentley, Feb 16, 2020

  • 2 Answers
  • 0
    I advise you to read for understanding:

    Object methods, "this" (RU)
    Arabella Beard

  • 0
    Wrong example (



    function a() {
    let self = this; // widnow
    console.log(this);
    var fn = function () {
    console.log(this); //widnow
    console.log(self); // function a - widnow
    };
    fn();
    }
    a();
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!