我想知道为什么这段代码有效:
class App extends React.Component {
render() {
return (
<div>
<Widget />
</div>
);
}
}
const Widget = () => {return <h1>hello</h1>};
我认为 const变量应该对App类(TDZ)不可见。
答案 0 :(得分:2)
const
变量,App
和Widget
在您的示例中属于同一范围
更新:
这种情况与babel或反应或webpack无关。
您只是混合了两个javascript概念calling
和defining
。您的示例可能看起来像这样,情况也是如此。
// function definition
function app() {
console.log(a);
}
// variable definition
const a = 2;
// function call
app();
此代码将2
记录到控制台。只有在a
函数调用时,Javascript才会尝试访问变量app
。
下一个例子
// function definition
function app() {
console.log(a);
}
// function call
app();
// variable definition and variable assignment
const a = 2;
,会将undefined
记录到控制台,因为在const a
分配
答案 1 :(得分:1)
Widget
在整个文件的范围内(常量是块范围的,但您已在最外层范围内声明Widget
。)
在调用Widget
之前,您无法访问render()
,到那时,它将被分配一个值。
答案 2 :(得分:1)
其他答案是正确但错误的。实际运行的代码中没有const
或class
。下面是执行的代码。
如果有疑问,请将代码粘贴到babel repl,然后您就会看到浏览器会执行的操作。
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var App = function (_React$Component) {
_inherits(App, _React$Component);
function App() {
_classCallCheck(this, App);
return _possibleConstructorReturn(this, Object.getPrototypeOf(App).apply(this, arguments));
}
_createClass(App, [{
key: "render",
value: function render() {
return React.createElement(
"div",
null,
React.createElement(Widget, null)
);
}
}]);
return App;
}(React.Component);
var Widget = function Widget() {
return React.createElement(
"h1",
null,
"hello"
);
};