javascript – 为什么使用胖箭而不是直接赋值?

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

为什么这样:

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

什么时候可以这样做?

const currentURL =  window.location.href;

解决方法:

第一个将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

相关文章

我最大的一个关于TypeScript的问题是,它将原型的所有方法(无...
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法...
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,...
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程...
我得到了一个json响应并将其存储在mongodb中,但是我不需要的...
我试图使用loadsh从以下数组中获取唯一类别,[{"listing...