简体   繁体   English

可以缩短此箭头功能吗? 这些都一样吗?

[英]Can this arrow function be shortened? Are these the same?

If I start with this: 如果我从这个开始:

const obj1 = {
    doSomething: () => {
        console.log('hello world 1');
    },
};

Can it safely be shortened? 可以安全地缩短它吗? Are these the same? 这些都一样吗?

const obj2 = {
    doSomething: () => console.log('hello world 2'),
};

Why is this one so strange? 为什么这个这么奇怪?

const obj3 = {
    doSomething: console.log('hello world 3'),
};

I noticed obj3 runs itself and can't do obj3.doSomething() . 我注意到obj3运行本身并不能做到obj3.doSomething()

https://repl.it/JEGD/1 https://repl.it/JEGD/1

1 and 2 are almost the same. 1和2 几乎相同。

When you provide a statement (instead of a block) on the RHS of the arrow, the function returns the result of evaluating that statement. 当您在箭头的RHS上提供一条语句(而不是一个块)时,该函数将返回评估该语句的结果。

In the first example, the function returns undefined because there is no return statement. 在第一个示例中,该函数返回undefined因为没有return语句。

In the second example, the function returns undefined because console.log returns undefined . 在第二个示例中,该函数返回undefined因为console.log返回undefined

There isn't a practical difference here, but there could be in similar cases. 这里没有实际的区别,但在类似情况下可能会有区别。


As for the third example… 至于第三个例子……

In case 1, you create a function with a function expression. 在情况1中,您将创建一个带有函数表达式的函数。

In case 2, you create a function with an arrow function. 在情况2中,您将创建一个带有箭头功能的功能。

In case 3, you don't create a function at all. 在情况3中,您根本不会创建函数。

You call console.log immediately and assign its return value (which, as I mentioned above, is undefined ) to doSomething . 立即调用console.log并将其返回值(如上所述,它是undefined )分配给doSomething

The reason that obj3.doSomething() is inoperable is because you are assigning the doSomething property of the object to the returned value of console.log(...) . obj3.doSomething()无法操作的原因是,您正在将对象的doSomething属性分配给console.log(...)返回值 Since console.log does not return anything, it simply executes and leaves doSomething empty. 由于console.log不返回任何内容,因此仅执行并将doSomething空。

obj1 and obj2 however are essentially the same thing. 但是obj1obj2本质上是同一件事。 If you were to replace console.log in obj2 with (x) => x * x , then the return is implied and not required, however surrounding the function body in {} like you have in obj1 would then still require the use of the return keyword. 如果要将obj2 console.log替换为(x) => x * x ,则意味着隐含且不需要return ,但是像您在obj1{}的函数体包含obj1 ,则仍然需要使用return关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM