[英]Creating a global variable from a function's return value
I'm looking at Addy Osmani's gist for a publication/subscription pattern here: 我在这里查看Addy Osmani的要旨,以进行发布/订阅:
https://github.com/addyosmani/pubsubz/blob/master/pubsubz.js https://github.com/addyosmani/pubsubz/blob/master/pubsubz.js
He surfaces his object as a global like this: 他将自己的对象作为一个整体显示为:
;(function ( window, doc, undef ) {
var topics = {},
subUid = -1,
pubsubz ={};
....
getPubSubz = function(){
return pubsubz;
};
window.pubsubz = getPubSubz();
What is the value of creating that getPubSubz
function? 创建该
getPubSubz
函数的价值是什么? Wouldn't it be more straightforward to simply write: 简单地写会不会更简单:
window.pubsubz = pubsubz;
Yes, in this case, because getPubSubz
is only called in one place, immediately after declaring it, it could safely be inlined. 是的,在这种情况下,因为仅在一个位置调用了
getPubSubz
,所以在声明之后立即可以将其安全地内联。
It's hard to say exactly what the author had in mind, but in a growing code base there may be some value to having a "getter" function which could be modified if the act of getting the pubsubz
object required more advanced logic. 很难确切地说出作者的想法,但是在不断增长的代码库中,拥有“ getter”功能可能会有一些价值,如果获取
pubsubz
对象的行为需要更高级的逻辑,可以对其进行修改。
It absolutely would be. 绝对会的。
There are only two potential reasons why a getter would be used in this case: 在这种情况下使用吸气剂只有两个潜在的原因:
Through the power of GitHub, we can actually eliminate option one , as the getter was added in its current state—so I think we can conclusively say that it's just a matter of good practice here. 通过GitHub的功能,我们实际上可以消除选项一 ,因为该吸气剂已添加到当前状态中-因此,我认为我们可以得出结论说,这只是一种良好的做法。
*as jantimon alludes to in the comments below, this isn't particularly advantageous in most cases (including this one) and this code does not necessarily need to followed as an example. *正如詹蒂蒙在下面的评论中所暗示的那样,这在大多数情况下(包括这一情况)并不是特别有利,并且此代码不必一定作为示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.