On some JS code on some sites I see Javascript code such as this:
SomeName.init = (function () {
// some stuff
})();
I mean, this is not a jQuery plugin code such as this:
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Then, what is it? and what is the resulting JS object?
Most JavaScript programs contain many JavaScript statements. The statements are executed, one by one, in the same order as they are written. JavaScript programs (and JavaScript statements) are often called JavaScript code.
The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object. It's used in OOP code, to refer to the class/object the function belongs to For example: function foo() { this. value = 'Hello, world'; this.
An identifier is a sequence of characters in the code that identifies a variable, function, or property. In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $ , _ , and digits (0-9), but may not start with a digit.
The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.
It's a anonymous function, which doesn't leak variables to the global scope when declaring variables using var
.
SomeName.init = (function () {
return 3.1415;
})();
SomeName.init
is a number (3.1415), because ()
after the anonymous function declaration executes the function. There's no way to obtain the original function, unless defined within the anonymous function:
(function foo(){
//foo refers to this function
too = foo;
})();;
//foo is undefined
//too refers to the function, because `too` has been defined without var
The Module Pattern. And those two snippets have more in common than you think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With