为什么使用粗箭头代替直接分配?

时间:2018-07-31 20:03:00

标签: javascript typescript

下面的代码段来自代码网站的30秒。这是一个初学者的例子,令人尴尬地让我难过。

为什么这样做:

const currentURL = () => window.location.href;

什么时候可以简单地做到这一点?

const currentURL =  window.location.href;

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

您看到的是功能的简写。

const currentURL = () => window.location.href;

翻译成

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

对此进行进一步扩展;这是给常量分配一个函数,该常量可以在以后调用以获取该值,而不是简单地分配它。由于函数的简单性,这不是您为什么要执行此操作的一个很好的示例,但是我认为作者只是试图说明如何执行此操作。

相关问题