为什么要使用“fat arrow”而不是直接赋值?

3
以下代码片段来自30秒代码网站。这是一个初学者示例,令我尴尬的是,我被卡住了。
为什么要这样做:
const currentURL = () => window.location.href;

当您可以简单地做到这一点时?
const currentURL =  window.location.href;

3
第一个设置currentURL为一个函数,该函数会计算出当前页面的URL地址,而第二个则直接将currentURL设置为window.location.href - zero298
我明白一个暗示了一个函数,但它们是否都有相同的净结果?做其中一个的好处是什么? - user796446
这只是一个过于简化的例子,这种情况并没有实际用途,但是它可以展示可能性。 - jrswgtr
它是 ES6 语言的一部分,简化了函数: https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/ const multiplyES6 = (x, y) => { return x * y };。这个例子对初学者来说很难读,但它确实能帮助你长期发展! - Igoranze
你能从链接的重复内容中添加一下,为什么你认为最终结果会是一样的吗?我不明白你是如何得出这个结论的。 - zero298
2个回答

4
第一个将 currentURL 设置为一个求值为 window.location.href 的函数,而另一个只是将 currentURL 设置为 window.location.href
考虑以下两者之间的区别:

/*
 * A function that will return the current href
 * returns {String}
 */
const currentURL1 = () => window.location.href;

/*
 * The current href
 * @type {String}
 */
const currentURL2 =  window.location.href;

console.log(currentURL1); // () => window.location.href
console.log(currentURL2); // https://stacksnippets.net/js

console.log(typeof currentURL1); // function
console.log(typeof currentURL2); // string

currentURL1(); // string
//currentURL2(); // error not a function


3
您所见到的是函数的简写形式。
const currentURL = () => window.location.href;

翻译成

const currentURL = function() { return window.location.href; }

进一步展开来说,这是将一个函数赋值给一个常量,以便在以后调用该函数以获取其值,而不是仅仅进行赋值。由于函数的简单性,这并不是为什么要这样做的好例子,但我认为作者只是试图说明如何实现这一点。

啊哈,我明白了...... currentURL 总是最新的......而另一个只是赋值一次?就是这样吗? - user796446
我想,解释一下它实际在做什么,将会说明为什么你会选择其中一个。也许我应该对答案进行扩展? - Adam H
@E.Maggini 不,它不会总是最新的。如果 window.location.href 改变(例如哈希部分),那么 currentURL 字符串就不会改变。但是如果调用函数,则会返回新值。 - Bergi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接