Javascript 为什么使用胖箭头而不是直接赋值?
下面的代码片段来自30秒的代码网站。这是一个初学者的例子,让我感到尴尬 为什么会这样:Javascript 为什么使用胖箭头而不是直接赋值?,javascript,typescript,Javascript,Typescript,下面的代码片段来自30秒的代码网站。这是一个初学者的例子,让我感到尴尬 为什么会这样: const currentURL = () => window.location.href; 你什么时候能简单地做到这一点 const currentURL = window.location.href; 您看到的是函数的简写 const currentURL = () => window.location.href; 转化为 const currentURL = function() {
const currentURL = () => window.location.href;
你什么时候能简单地做到这一点
const currentURL = window.location.href;
您看到的是函数的简写
const currentURL = () => window.location.href;
转化为
const currentURL = function() { return window.location.href; }
在这一点上再进一步扩展;这是将一个函数赋给一个常数,该常数可以在以后调用以获取值,而不是简单地赋给它。这不是一个很好的例子来说明为什么要这样做,因为函数很简单,但我认为作者只是想说明如何做到这一点 第一个将
currentURL
设置为计算结果为window.location.href
的函数,另一个将currentURL
设置为window.location.href
考虑以下两者之间的差异:
/*
*将返回当前href的函数
*返回{String}
*/
const currentURL1=()=>window.location.href;
/*
*当前href
*@type{String}
*/
const currentURL2=window.location.href;
console.log(currentURL1);//()=>window.location.href
console.log(currentURL2);//https://stacksnippets.net/js
console.log(currentURL1的类型);//功能
console.log(currentURL2的类型);//一串
currentURL1();//一串
//currentURL2();//错误不是一个函数
第一个将currentURL
设置为一个计算结果为window.location.href
的函数,另一个只将currentURL
设置为window.location.href
。我知道其中一个的可能重复意味着一个函数……但它们的净结果不一样吗。这样做的好处是什么?这是一个过于简化的例子。这个场景实际上没有用,但它是为了展示这种可能性。它是ES6语言的一部分,并简化了函数:constmultiplyes6=(x,y)=>{return x*y}代码>。所使用的示例除了对初学者来说很难阅读之外,没有添加任何内容。但从长远来看,它确实对你有帮助!啊,我现在明白了。。。。。。currentURL将始终是最新的…另一个只分配一次?是吗?我想关于它的实际作用的解释可以解释为什么你会做一个而不是另一个。也许我应该详细介绍一下答案?@E.Maggini不,它并不总是最新的。如果window.location.href
更改(例如哈希部分),则currentURL
字符串不会更改。但是如果调用,函数将返回新值。