有人可以解释这两个JS代码片段之间的区别吗?

Could someone explain the difference between these two JS code snippets?

本文关键字:片段 代码 JS 之间 区别 两个 解释      更新时间:2023-09-26

有人可以解释这两个代码片段之间的区别吗?是否有任何真正的功能差异?一个比另一个优越吗?

isIPad = function() {
    return navigator.userAgent.match(/iPad/i) != null;
};

isIPad = (function isIPad() {
    return navigator.userAgent.match(/iPad/i) != null;
}());

第一个变量将存储一个函数,该函数将根据设备是否为 iPad 返回布尔值。

var thisIsAnIPad = isIPad()
if(thisIsAnIPad) {
  console.log('This is an iPad!');
}

第二个变量立即计算布尔结果并将其存储。您可以直接使用该值。

if(isIPad) {
  console.log('This is an iPad!');
}

这两种方法在客观上都不优越。它们都有不同的用例。例如,如果您只想在某个时间点知道用户是否在iPad上,则可以使用第二个选项。

如果它是一个需要多次重新计算的值(也许用户代理正在更改?(,那么第一个选项更可取。

但是,第二种方法可以简化为

isIPad = navigator.userAgent.match(/iPad/i) != null;

这将比其他任何选项都更节省内存。