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