为什么这在反应组件方法中解析为 undefined not window/global-env 如果它没有在构造函数中绑定它

why this resolves to undefined not window/global-env in react component method if it not bind this in constructor

如标题所述。

我得到了如何解决这个问题的答案 - this 指的是 undefined

但是没有答案告诉我为什么 this 指的是 undefined

在我看来,如果没有隐式或显式指定,this 将指代 window/global-env

当然,在 strict-modethis 将是 undefined

这是在运行时确定的,根据代码,它可能有所不同。

这是

  • 在调用函数时在运行时确定
  • 取决于函数的调用方式,而不是函数所在的位置 定义
  • 对对象的引用。
  • 永远是一个对象
  • 全局(this)在严格模式下不可用

示例 1:这个 = window

var name = 'Global';

var callName1 = function() {
  var name = 'Peter';
  console.log('--- From callName1 ----');
  console.log(this.name);
  //console.log(this);
  callName2();
}


var callName2 = function() {
  var name = 'Jane';
  console.log('--- From callName2 ----');
  console.log(this.name);
  //console.log(this);
}

callName1();

var execute = function(fn) {
  var name = 'Mary';
  console.log('--- From execute ----');
  console.log(this.name);
  //console.log(this);
}

execute(callName2);

示例 2:在严格模式下不可用

'use strict';

var name = 'Global';

var callName1 = function() {
  var name = 'Peter';
  console.log('--- From callName1 ----');
  console.log(this.name);
  console.log(this);
}

callName1();

示例 3:使用方法调用检查 this

var name = 'global';

var obj = {
  name: 'James Obj1',
  func: function() {
    console.log('--- From func ----');
    console.log(this.name);
    console.log(this); // this reference obj1
  }
}

obj.func()

var obj2 = {
  name: 'Jame Obj2',
  func: obj.func // this reference obj2, but the function is defined in obj1
}

obj2.func()

var obj3 = {
  name: 'Kane Obj3',
  obj4: {
    name: 'Mary Obj4',
    func: function () {
      console.log('--- From obj4 ----');
      console.log(this.name);
      console.log(this); // this reference obj4
    }
  }
}
obj3.obj4.func()

With () => {} 函数 this - 是词法绑定的。这意味着它使用了包含箭头函数的代码中的 this

使用下面的代码验证方法是否处于严格模式。

在方法中包含以下代码。

出现类型错误,这意味着,方法处于严格模式,这解决了混淆问题。

var obj2 = { get x() { return 17; } };
obj2.x = 5;