Shaz

Global Moderators
Global Mod
Joined
Mar 2, 2012
Messages
42,464
Reaction score
14,816
First Language
English
Primarily Uses
RMMV
Could someone please kindly provide a summary of the benefits of using the following structure for plugins?

Code:
(function() {
  // stuff goes here
})();

I've seen plugins that use it, and plugins that don't. Some plugins put some stuff outside of it, and others put the same stuff inside. What's the difference? If I'm overriding or aliasing the functions in the core files, does it matter whether I use the above structure or not?

Some plugins do weird things like this:

Code:
(function(_) {
 // stuff goes here
})(something);

and I think I've seen some that do this:
Code:
(function($) { ...

What's that all about - what does it allow you to do? What's the significance of what I put in the ()?

I'm starting to write new plugins for my own game, which I may share here, and I'd like to get off on the right foot.
 

BigEd781

undefined method 'stupid_title' found for nil:NilC
Veteran
Joined
Mar 1, 2012
Messages
940
Reaction score
304
First Language
Dothraki
Primarily Uses
N/A
It's called an immediately invoked function expression. JS devs (of which I am not one...) use that to scope everything declared inside the function to the function itself (i.e., it doesn't pollute the global scope.) It also means that you don't have to give a name to the function, so it cannot be called again later in code (when you may not want it to be called again for whatever reason.) Think of it as an inline anonymous function.

Whether or not those MV scripts are using it correctly or just copying something they've seen elsewhere... I can't say. Probably a little of both.

P.S. Hey Shaz! Long time.
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,634
Reaction score
1,452
First Language
French
Primarily Uses
RMMV
Last edited:

Shaz

Global Moderators
Global Mod
Joined
Mar 2, 2012
Messages
42,464
Reaction score
14,816
First Language
English
Primarily Uses
RMMV
I know what this is:
Code:
// not executed when read, but storing, and wait for call
function name(){
// do something
};

name(); // now its execute

I was asking what this is:
Code:
(function ($) {
})(somename)

which is not the same.


Checked the links - they did not answer my questions. Thanks though.
 

Llareian

Jack of All Trades, Master of None
Veteran
Joined
Jan 26, 2017
Messages
608
Reaction score
1,432
First Language
English
Primarily Uses
RMMZ
From what I've been able to decipher, $ is the parameter for the function, and somename is the argument passed into the function (as $). Otherwise, BigEd781's explanation of scope and the fact that the function is immediately executed are spot on.

In other words:
Code:
var somename = "Shaz is great!"

(function($){
    console.log($);    //prints "Shaz is great!"
})(somename)
 

Shaz

Global Moderators
Global Mod
Joined
Mar 2, 2012
Messages
42,464
Reaction score
14,816
First Language
English
Primarily Uses
RMMV
Ahhh ... I thought it was something that would allow you to run functions from outside of the plugin - I seem to remember something like this:

Code:
(function($) {
  myfunction = function(args) {
    // do stuff
  }
})(runme);

runme.myfunction();

However, your example, @Llareian , would be really easy to test! But how do you call it / tell it to run?
 

Llareian

Jack of All Trades, Master of None
Veteran
Joined
Jan 26, 2017
Messages
608
Reaction score
1,432
First Language
English
Primarily Uses
RMMZ
It should run automatically! That's why it's called an Immediately Invoked Function Expression (IIFE). I THINK the only difference to writing:
Code:
var somename = "Shaz is great!"

var myFunction = function($) {
    console.log($);
}

myFunction(somename);
...is the scope issue for variables defined inside the function, as BigEd781 was saying.

Edit: And the ability to call the function again later...
 

Shaz

Global Moderators
Global Mod
Joined
Mar 2, 2012
Messages
42,464
Reaction score
14,816
First Language
English
Primarily Uses
RMMV
okay - then what is the point? What's the advantage of writing it like that? If it's going to run automatically, immediately, and not allow me to call it, why would I bother passing anything in? Why not just put the text into the function itself? I can't change the variable and call it again later.
 

Fhntop

Villager
Member
Joined
May 4, 2017
Messages
28
Reaction score
25
First Language
Spanish
Primarily Uses
RMMV
I think this can be used as a way to limit what you want to be accessible from the outside.

For instance, taking your example:
Code:
var module = (function(exp) {
    var j = 0;
    exp.inc = function(args) {
      j ++;
      return j;
    }
 
    exp.dbl = function(args) {
      j *= 2;
      return j;
    }

    function reset() {
      j = 0;
    }
 
    return exp;
})({});

console.log(module.inc());
console.log(module.inc());
console.log(module.dbl());

I haven't used this but I've seen it in several libraries as well. I think it might also prevent changing the module's code from the outside but I'm not sure...
 

LTN Games

Indie Studio
Veteran
Joined
Jun 25, 2015
Messages
708
Reaction score
636
First Language
English
Primarily Uses
RMMV
All it is, is a global variable and yes you can use it to run stuff outside the function. It's really no different than declaring a variable outside the iife and then assigning the functions to that variable.

I do it this way because I started with my first few plugins and kept the consistency but TBH it's pointless and probably easier to read the code if you just use the variable name on all functions and variables you want to be available outside of the iife.
 

Shaz

Global Moderators
Global Mod
Joined
Mar 2, 2012
Messages
42,464
Reaction score
14,816
First Language
English
Primarily Uses
RMMV
thanks. I don't plan on making the functions available outside of the plugin, so I suppose there is no reason for me to use that syntax.
 

Bigbaddevil7

Aka SteamPunkDevil
Member
Joined
Jan 30, 2017
Messages
18
Reaction score
2
First Language
English
Primarily Uses
RMMV
Hopefully this isn't too long since last post, but really felt this should be added for anyone that can stumble across this thread.

All the $ is, is a JavaScript Identifier same as the _ for JavaScript.

The $ is pretty much a base Object for other Libraries.

It also depends on what kind of background the Dev's come from, something like:
Code:
$(document).ready(function () {
});
would be extremely common in Web development.

As well as using the $ helps with using stuff such as:
Code of my own work

JQuery (it is used to simply replace the need to say JQuery at the beginning)
Code:
$(".HIP").show("slide", {direction: "down"}, 500);

Ajaxing.
Code:
$.ajax({
    url: 'admin/twitchAjax.php?f=IDToUsername&user=' + userID,
    type: 'POST',
    cache: false,
    success: function ($dpcaller) {
        if ($dpcaller) {
            document.getElementById("dpname").innerHTML=$dpcaller;
            // dpanimate();
        }
     }


There are points where JS function may need to have an invoked or callback function built into as it gets self referenced. A lot of the stuff is not necessary for this case use as we are not using additional Libraries usually.

On top of all that Since JS has went though a lot of changes with the Newest EMC6 allowing for Classes, you are also seeing old practices vs new practices. Some of that use to be the norm.
 
Last edited:

BlueMoon

Nebula Games Leader
Veteran
Joined
Jan 10, 2017
Messages
349
Reaction score
475
First Language
Italian
Primarily Uses
RMMZ
Code:
var Gamefall = Gamefall || {};
Gamefall.CustomObj = Gamefall.CustomObj || {};
(function($) {
code...
})(Gamefall.CustomObj)

When I develop plugin I generally work this way.
Declaring the $ argument inside the closure allows to store the contents of the closed scope inside an object (Gamefall.CustomObj) that I create for each plugin.
This is very useful for having control on the variables of your scope and for your alias, because, inside the caption:

Code:
var testAlias = code...
// Can't be tested in console

$.testAlias = code...
// Can be tested in console with Gamefall.CustomObj.testAlias

I really suggest this way of work, because saves you time and It makes the codes better polished.

Another thing I really suggest, It's to create classes outside the scope, this way you can access them in other plugins.

Ex.
Code:
function Window_Test() {
this.initialize.apply(this,arguments)
};

(function($) {
Window_Test.prototype = Object.create(Window_Base.prototype)
etc..
})(Gamefall.CustomObj)

If you proceed this way:
Code:
(function($) {
function Window_Test() {
this.initialize.apply(this,arguments)
};

Window_Test.prototype = Object.create(Window_Base.prototype)
etc..
})(Gamefall.CustomObj)

Window_Test will be not available for making changes in its prototype in other plugins.

WARNING!
Pay attention to the ; comma for the elements before the closure!

Code:
var Gamefall = Gamefall || {}

//No comma at the end of the var

(function($) {
code...
})()

//The code will give you error

Right Way:

Code:
var Gamefall = Gamefall || {};

//Comma at the end of the var

(function($) {
code...
})()

//No error
 

Latest Threads

Latest Profile Posts

i want to make videogame, though i am burned out on games with RPG elements, but the only gamedev tool i know how to use is rpg maker. :/
Rakon wrote on xizorandy's profile.
Hello! I found a post of lightning strike pictures you posted. You said you made them, am I allowed to use them in my commercial project. Would be really cool!^^
evhht2zr.png

Have a nice day!
It's almost 3 month and this piece of drawing is still not finished yet.
aaaa.jpg

Really busy with other stuffs like commission and coping with personal problem.
Stella & Elyune, maybe used for promotional art if my game project finished one day.

Forum statistics

Threads
112,253
Messages
1,066,840
Members
145,860
Latest member
tommyelliott
Top