javascript - ES6函数声明困难

标签 javascript ecmascript-6

我正在学习 React Native 类(class),并意识到讲师以两种不同的方式声明函数,原因似乎没有什么不同。请解释何时应使用每个函数声明:

example = () => ();

对比

example = () => {};

谢谢

最佳答案

箭头函数在 function bodies 中可能有所不同(谢谢罗比)。 简洁函数体只能包含一个被计算并隐式返回的表达式。传统的block函数体需要return关键字,否则将返回void

example1 = () => 1 + 1;

example2 = () => {
    const result = 1 + 1;
    return result;
};

example3 = () => { 
    const result = 1 + 1;
};

example1() 具有简洁的主体,并且将隐式返回表达式 2 的结果。
example2() 有一个 block 体并且显式返回2
example3() 有一个 block 体并且没有显式返回,因此它返回void

请注意,如果您想返回对象字面量,则需要在简洁函数体周围使用普通大括号():

example = () => ({some: 'object'});

关于javascript - ES6函数声明困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183780/

相关文章:

Javascript:在同一行中声明一个变量两次 - 这意味着什么(例如 Var x = this.time = this.time || this.time(); )

javascript - React Redux-我的 Action 创建者没有将 Action 传递给 reducer (同步)

javascript - 使用 codeigniter 从数据库中选择相关选项

javascript - 如何在没有css文件的情况下动态地将css添加到ckeditor

javascript - ReactJS:使用 map 渲染带有键的对象

javascript - 使用 node_modules/中的 ES6 文件运行 Mocha 时出错

javascript - 使用 'let' 作为变量名不会在 google v8 中引发任何错误

javascript - 聚合一个对象,其中每个键的值都是对象数组

javascript - React.DOM : Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

javascript - 避免黑客正确绑定(bind)到 ES6 中的类?