Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: "Top-level 'this' expression"

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.

like image 850
Nadav S. Avatar asked Nov 07 '12 19:11

Nadav S.


3 Answers

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.

(function(window, undefined) {
})(this);

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

function my_func(window, undefined){...}
my_func(this);

Now to explain the this. Usually, we wrap our entire program in such a self-executing function. The this while 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

window = 0;
//or
undefined = 1;

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.

like image 162
Naman Goel Avatar answered Nov 06 '22 11:11

Naman Goel


It's complaining that you're using this outside of any function.

Inside a function, the use of this (generally) means that the programmer intended the function as a method (where this is the object that the method is called on), but outside a function, it's just a strange thing to do.

It's better to write window instead, to explicitly refer to the global object, rather than to rely on the fact that this implicitly refers to the global object when it's not used in a method call.

like image 28
ruakh Avatar answered Nov 06 '22 11:11

ruakh


This puts a whole chunk of code into a immediately executing function with its own scope.

For example:

(function(w){
    var apple = 'apple';
})(window);

alert(apple); //undefined
like image 41
Naftali Avatar answered Nov 06 '22 11:11

Naftali