javascript - 为什么使用粗箭头而不是直接赋值?

标签 javascript typescript

以下代码片段来自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

关于javascript - 为什么使用粗箭头而不是直接赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621208/

相关文章:

javascript - 对象取消订阅错误: object unsubscribed

TypeScript 模块扩充会覆盖原始模块吗?

javascript - 无法访问 documentReady() 中的 div

javascript - 我可以从 ionic 应用程序移植到 react native 或在 react native 中重用 ionic 代码吗?

php - 在 Javascript 中使用 PHP?缩小网址

javascript - jQuery如何从单选按钮获取div元素值并将值分配给特定div

javascript - Vue i18n with TypeScript : "Property ' $t' does not exist on type 'VueConstructor' . 时出错“。我该如何修复它?

javascript - 我可以在可变高度的 div 上使用 `overflow: scroll` 吗?

reactjs - 类型 '{ src: String; }' 不可分配给类型 'SVGProps<SVGImageElement>

typescript - 如何编写启用 no-unsafe-any 的类型保护?