箭头函数中的 this 关键字在当前上下文中正常工作,但在 chrome 调试器控制台中显示不正确的值

this keyword in arrow functions work correctly on current context but show incorrect value in chrome debugger console

我正在研究 React 中的 ES6 箭头函数。箭头函数中的 'this' 关键字在 chrome 调试器控制台中显示得很奇怪。 'this' 在当前对象上下文中工作正常,但是当在 chrome 调试器控制台中检查该值时,它显示不正确的值。

我已经检查了 How does the "this" keyword work? 但这并没有回答我的问题。我的问题不是这个关键字是如何工作的,而是它在控制台中显示的奇怪值。

在调试器控制台中,它显示为引用 window 但通过指向当前实例可以正常工作。

我别无选择,只能制作一个视频来演示这个问题。如果有 Javascript 专家帮助我解决这个问题,我将不胜感激。

https://youtu.be/FyF-DK8xcpg

代码:

import React, { Component } from 'react';

class App extends Component {

  state = {name: "Rahul"}

  nameChanger = () => {
    debugger;
    console.log("This is" + this.Window.name);
    this.setState({name: "New Rahul"})
  }


  render() {

    setTimeout(this.nameChanger, 1000);

    return (
      <div className="App">
         {this.state.name}
      </div>
    );
  }
}

export default App;

上面的react代码其实是webpack编译出来的(我之前应该已经提供了这个信息)成:

var App = function (_Component) {
  _inherits(App, _Component);

  function App() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, App);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = App.__proto__ || Object.getPrototypeOf(App)).call.apply(_ref, [this].concat(args))), _this), _this.state = { name: "Rahul" }, _this.nameChanger = function () {
      debugger;
      _this.setState({ name: "New Rahul" });
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(App, [{
    key: "render",
    value: function render() {

      setTimeout(this.nameChanger, 1000);

      return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(
        "div",
        { className: "App", __source: {
            fileName: _jsxFileName,
            lineNumber: 17
          },
          __self: this
        },
        this.state.name
      );
    }
  }]);

  return App;
}(__WEBPACK_IMPORTED_MODULE_0_react__["Component"]);

/* harmony default export */ __webpack_exports__["a"] = (App);

原始问题中的代码只是一个源映射(在 chrome 开发人员工具设置中启用)。我不确定 webpack 是否是这里的罪魁祸首,因为它创建了一个新的 '_this' 来保存当前上下文,保持原始 'this' 不变(指向 window 对象)。因此,当您调试源映射时,chrome 调试器会在控制台中显示原始的 'this' (window),但会在当前上下文 (_this) 中执行语句。