Monday, November 11, 2013

Sharing: Self Invoked Object Literals

Some techniques aren't new or novel. They are just fun. This isn't really new, or novel either, but it's quite fun.

~{
func: function(){
alert("hello world!")
}
}.func();
view raw example.js hosted with ❤ by GitHub

In fact, some people would probably criticize that it is essentially the same thing as an Immediately Invoked Functional Expression. There are some key differences here though. Take a look at the following code.

var foo = {
bar: {
//put some named functions here
},
baz: function(){
return Object.create(this.bar);
}
}.baz();
view raw example-2.js hosted with ❤ by GitHub

It's starting to look like the module pattern, but it creates an object and ships it via function baz to the variable foo with bar's prototype. Alas, the this keyword shows it's confusing head again, but look closely. "this" is the object literal itself.

Finally I'll leave you with a working example.

!{
//Typical API functions should go here
//func : function(){}....
//func2 : function(options){...}
//Object creation methods...
//convenience methods here for create and expose via this
createObject: 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, target, plugins){//initialization code.
target[NameSpace] = this;//target can be the window (exposed) or some other object
this.plugins = plugins;
delete this.expose; //remove the reference to expose
}
}.expose("LibraryNamespaceHere", {}, []);

Sometimes, the "new" keyword is overrated when making objects anyway.

In functional health,
-Josh

No comments:

Post a Comment