I get the following warning/hint/error when I have an object like this:
(
function global(){...};
function moreFunctions(){...};
)(this);
“Top-level ‘this’ expression. This inspection reports instances of Javascript ‘this’ expression occuring outside of object literals or constructor bodies. Such this expressions are legal Javascript, and reference the top-level “global” Javascript object, but are largely useless.” (by InspectionJS)
By the way, jQuery has the same with (window) instead of (this).
I don’t understand what it means. All I know is that everthing between the first ( and second ) is an object, but what’s that addition?
I’ve got into this because I’ve just discovered a JS library source and somehow when it is included in my existing scripts everything just stops working. When I deleted that (this); part it didn’t crash the page; but the library just didn’t work.
I’m not 100% sure on the problem you’re having but let me explain what I learned from Paul Irish’s video on lessons from the JQuery source.
This is known as a self-executing function. The function definition is put in brackets. (anything can be put in brackets in Javascript almost all the time). Then, the second
()immediately calls the function.so it’s like doing the following
Now to explain the
this.Usually, we wrap our entire program in such a self-executing function. Thethiswhile calling, and the window and undefined are pretty much just fixes for edge-cases when sharing the code space.For example, someone could put something like
suddenly, these very important global variables we rely on break. using this at the top level returns the window variable to the inner function. And since we don’t pass any second variable to the function, undefined is back to its correct value.
Hope all this helped.