// bad
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}
// bad (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
这取自 Airbnb React 风格指南。有人可以解释为什么“不鼓励依赖函数名称推断”吗?这只是风格问题吗?
最佳答案
我认为这也可能与您可能会遇到的意外行为有关,因为您可能会隐式地为您可能认为是匿名函数的函数提供词法名称。
比如说有人理解箭头函数:
(x) => x+2;
要使常规函数等效:
function(x) {
return x+2;
}
很容易期待这段代码:
let foo = (x) => x+2;
然后相当于:
let foo = function(x) {
return x+2;
}
函数保持匿名并且无法引用自身来执行递归等操作。
如果那时,在我们幸福的无知中,我们发生了这样的事情:
let foo = (x) => (x<2) ? foo(2) : "foo(1)? I should be a reference error";
console.log(foo(1));
它会成功运行,因为该函数显然不是匿名的:
let foo = function foo(x) {
return (x<2) ? foo(2) : "foo(1)? I should be a reference error";
}
这可能会因为在其他情况下 Babel 隐式地为匿名函数添加名称而加剧(我认为这实际上是首先支持隐式函数名称的副作用,尽管我可能是错误的),他们正确地处理任何边缘情况并在您期望的地方抛出引用错误。
例如:
let foo = {
bar: function() {}
}
// Will surprisingly transpile to..
var foo = {
bar: function bar() {}
};
// But doing something like:
var foo = {
bar: function(x) {
return (x<2) ? bar(2) : 'Whats happening!?';
}
}
console.log(foo.bar(1));
// Will correctly cause a ReferenceError: bar is not defined
您可以在此快速 DEMO 上检查“查看已编译”看看 Babel 实际上是如何转换它以保持匿名函数的行为。
简而言之,明确说明您正在做什么通常是个好主意,因为您确切地知道您的代码会带来什么。不鼓励使用隐式函数命名可能是支持这一点的一种风格选择,同时也保持简洁明了。
可能还有吊装。但是,嘿,有趣的旅行。
关于javascript - 为什么 Airbnb 风格指南说不鼓励依赖函数名称推断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37288950/