将 IIFE 的公共成员分配给变量与返回对象有什么区别
我最近查看了大量 JavaScript 代码,并且看到了使用分配 IIFE 的“公共”属性的两种不同方法。
第一种是创建一个变量并将该变量分配给 IIFE 内部的属性,如下所示:
var public1;
(function(){
var foo= "Foo", bar= "Bar";
public1= {
getFoo: function(){
return foo;
}
};
}());
我看到的第二种方法是从 IIFE 返回一个对象,如下所示:
var public2 = (function(){
var foo2= "Foo2", bar2= "Bar2";
return {
getBar: function(){
return bar2;
}
};
}());
这两种方式之间是否存在根本区别,或者只是一个偏好问题?我还创建了一个小提琴,以便您可以根据需要运行或更新代码: http:// /jsfiddle.net/bittersweetryan/gnh79/3/
I've been looking at a lot of JavaScript code lately and I've seen two different ways of using assigning "public" properties of IIFE's.
The first is to create a variable and assign that variable to a property inside of the IIFE like so:
var public1;
(function(){
var foo= "Foo", bar= "Bar";
public1= {
getFoo: function(){
return foo;
}
};
}());
The second way I see is returning an object from the IIFE like so:
var public2 = (function(){
var foo2= "Foo2", bar2= "Bar2";
return {
getBar: function(){
return bar2;
}
};
}());
Is there a fundamental difference between these two ways or is it just a matter of preference? I've also created a fiddle so you can run or update the code if you'd like: http://jsfiddle.net/bittersweetryan/gnh79/3/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有什么区别。
但我认为第二个更容易维护。当您更改第一个示例中的变量名称时,您也必须在函数中更改它。
There is no difference.
But I'd argue that the second one is a bit easier to maintain. When you change the variable name in the first example, you have to change it in the function as well.