这段代码有什么作用?它的实际用途是什么?这段代码不是我写的。我在这里找到它:https://gist.github.com/anonymous/7407896
!{
//convenience methods here for create and expose via this
create: function(options){
//constructor logic here
var created = Object.create(this.fn);
var args = [].slice.call(arguments);
this.plugins.forEach(function(plugin){
plugin.apply(created, args);
});
return created;
},
fn:{//prototype methods here
},
expose:function(NameSpace, window, document, plugins){
window[NameSpace] = this;//This can be tweaked for whatever
this.document = document;
this.plugins = plugins;
}
}.expose("LibraryNamespace", window, document, []);
我很想知道上面的方法比做揭示模块模式之类的事情更好。我也不清楚 create 函数的机制。有人可以引导我完成根据传入的原型(prototype)创建对象的过程吗?
var libraryNameSpace= window.libraryNameSpace || {};
libraryNameSpace.myFeatureOne = (function(){
var _bar = "_bar";
var foo = "foo" + _bar;
function foobar(){ return "foobar"; }
return {
myFoo : foo;
fooBarMethod: foobar;
};
})();
最佳答案
第一个代码块首先返回一个具有三个函数的对象,然后调用公开函数,该函数是根据参数返回对象的构造函数。 hide 函数会将此对象及其命名空间添加到窗口对象中。 当将库放入窗口对象时,这段代码似乎很有用。
在第二个代码块中,您将变量名libraryNameSpace 声明为window.libraryNameSpace 或空对象。由于此时 window.libraryNameSpace 可能尚未定义。它将把变量设置为对象。然后您将在该对象上添加一个自调用函数。
主要区别在于处理对象的方式。 {}、Object.create、new ConstructorFunc() 之间有区别,还有可变性
关于javascript - 立即调用对象字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280252/