Explanation for changing the value of `this` in the following code snippet?

function wrap(func) {
  console.log('0', this)
  return function x() {
    console.log('1', this)
    func()
    return function z() {
      console.log('3', this)
    }
  }
}

var obj = {
  x: 5,
  test: wrap(function y() {
    console.log('2', this)
  })
}

obj.test()()

Code above logs

// 0 Window
// 1 Object
// 2 Window
// 3 Window

I am having trouble understanding what defines value this.

// 0 Windowmakes sense because this is when wrap is first called, and at that moment its value thisshould not be set toobj

// 1 Objectit makes sense obj.testnow equals function x()that correctly registers thisasobj

// 2 WindowI do not know why this is happening. Why thisdoes the value not apply to func()? I thought I thisshould have referenced the owner of the function. Does this mean that even if it function y()was created inside obj, it was somehow raised to the window?

// 3 Window function z() this function x(). this?

+4
2

, this, desugar

  • wrap.call(window, function() {})
  • obj.test.call(obj)
  • y.call(window)
  • z.call(window)

, this . this , .

, , , , this.

function wrap(func) {
  return () => {
    console.log(this)
    return () => {
      console.log(this)
      func()
      return () => console.log(this)
    }
  } 
}

function wrap(func) {
  var _this = this;

  return function () {
    console.log(_this);
    return function () {
      console.log(_this);
      func()
      return function () {
        return console.log(_this);
      };
    };
  };
}

, this. , func this. func.call(this), .

0

'this' . , , . Javascript, 'this':

  • ,
  • default ()

β„– 3 β„– 4, .

, :

//0 - # 4 ()

//1 Object-rule # 3 , , obj.test

//2 - # 4 ()

//3 - # 4 ()

0

All Articles