I was reading over how to 'Create a JavaScript Library' earlier and I came across these pieces of code that make me wanna rip my hair out.
Here is the code which got my brain in knots:
if (window === this) {
return new _(id);
}
_(id) is just the function name in which this code is contained. Here's the rest of the code if you need to look over it yourself.
function _(id) {
// About object is returned if there is no 'id' parameter
var about = {
Version: 0.5,
Author: "Michael Jasper",
Created: "Fall 2010",
Updated: "23 November 2011"
};
if (id) {
// Avoid clobbering the window scope:
// return a new _ object if we're in the wrong scope
if (window === this) {
return new _(id);
}
// We're in the correct object scope:
// Init our element object and return the object
this.e = document.getElementById(id);
return this;
} else {
// No 'id' parameter was given, return the 'about' object
return about;
}
};
I've never seen 'return new function' before but I would love to understand how it functions.
The other piece of code:
_.prototype = {
hide: function () {
this.e.style.display = 'none';
return this;
}
show: function () {
this.e.style.display = 'inherit';
return this;
}
};
I know that this code adds new methods to the _ object but why do they 'return this'? I tried that without and it worked just fine.
One last thing, the link to the article is http://www.mikedoesweb.com/2012/creating-your-own-javascript-library/