简体   繁体   English

JavaScript中的函数调用差异

[英]Function call difference in javascript

What is the difference between these two and why would you use one over another? 两者之间有什么区别,为什么您要一个又一个地使用?

MYUtils.isIOS = (function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
}());

var ios = MYUtils.isIOS;

vs

MYUtils.isIOS = function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
};

var ios = MYUtils.isIOS();

In this example, there is no strong reason to use one over the other. 示例中,没有充分的理由使用一个在另一个之上。

The first example runs, and sets the value. 第一个示例运行并设置值。 The value, from that point on, does not change. 从那时起,该值不变。

In the second example, every time you call isIOS() , you are running the inner function. 在第二个示例中,每次调用isIOS() ,您都在运行内部函数。 navigator.userAgent is not going to change at some point during your page life, so the result won't change. navigator.userAgent在页面生命中的某个时候不会改变,因此结果不会改变。

However, should you be looking for some value that can change, perhaps checking if a certain HTML checkbox is set, or looking for a value set in localStorage then the second way is better, because you allow for a changing environment. 但是,如果您正在寻找可以更改的值,例如检查是否设置了某个HTML复选框,或者在localStorage查找一个值设置,那么第二种方法会更好,因为您允许更改环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM