微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐