1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Javascript closure

Discussion in 'JavaScript' started by serialentre, Mar 8, 2015.

  1. serialentre

    serialentre Member

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    30
    #21
    Yes it makes sense to me! I followed along without much difficulty, thankfully!

    In summary -

    1. ALL functions are objects
    2. It's ideal to create Constructor Functions/Objects because you only create new objects when you need, and reduce memory wastage

    I have two simple questions -

    1. I've seen people creating anonymous functions like this -


    (function () {
    insert code here
    }();
    Code (markup):
    Why is the function created as such?

    2. Simple question regarding the object found in 'return'. My understanding of creating object literals are as such

        var exampleObject () {
            getID: function ()  {
                // This inner function will return the UPDATED celebrityID variable
                // It will return the current value of celebrityID, even after the changeTheID function changes it
              return celebrityID;
            },
            setID: function (theNewID)  {
                // This inner function will change the outer function's variable anytime
                celebrityID = theNewID;
            }
        }
    Code (markup):
    But in the example that I copied and which you expanded upon, what is the code (getID and setID) found within return brackets? It looks like object literals but there is no variable or function before getID and setID.

        return {
            getID: function ()  {
                // This inner function will return the UPDATED celebrityID variable
                // It will return the current value of celebrityID, even after the changeTheID function changes it
              return celebrityID;
            },
            setID: function (theNewID)  {
                // This inner function will change the outer function's variable anytime
                celebrityID = theNewID;
            }
        }
    Code (markup):
     
    serialentre, Mar 15, 2015 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #22
    The wrapping () and trailing () means the function runs right then and there. They are called "self executing anonymous functions" -- As a declared function/object it's namespace and values are not released, creating, well... basically a little isolated scope. Anything declared as VAR, "this." or functions inside that object are not exposed outside of it. Basically it isolates that code so no other scripts can interfere with what it's doing.

    Little word of warning -- A LOT of people hear that "anonymous functions waste memory when created more than once" and magically translate it in their heads to "never use anonymous functions" or "anonymous functions are evil" out of ignorance, stupidity, or just a lack of command of the language they are reading. The same way some ignorant dipshits translate "tables for layout is bad" into "never use tables" or "use EM or STRONG when providing emphasis" into "Never use B or I" -- Completely misunderstanding / misinterpreting / corrupting what's being said.

    If it's only being called and/or created ONCE, there's nothing wrong with it. If you are using it instead of a named function for a reason (like it being different every time or to isolate scope of that instance) there's nothing wrong with it. But... you start using them and saying "anonymous function"? Typically at least one whackjob from the peanut gallery will chime in with an attack against them out of ignorance and/or failing to grasp the simplest of concepts.

    I use SEAF all the time as I like the idea of not putting anything into the global namespace I don't have to. They're also nice to run right before </body> so you don't have to (in most cases) dick around with onload since the DOM is already built at that point.

    You've at least heard of JSON, right? You know what it stands for? JavaScript Object Notation. It is based on what are called "Literal Objects" in JavaScript. Remember above where I gave ALL those examples of what constitutes an object? Look VERY close at the last one.

    For example:

    var pet = {
    	name : 'Maddy',
    	gender : 'cat',
    	sex : 'female',
    	age : 10
    };
    
    alert(pet.name);
    Code (markup):
    It's an object, we can access it as an object. Objects can be assigned to variables, evaluated, or passed anyplace a parameter is passed because, well... another oddball thing in JavaScript is that all variables are ALSO objects. You don't have to say "function" to create an object, you only need function if you are going to have code run when it's called/created.

    Let me just say that again, in JavaScript ALL variables are also objects and inherit object methods from String, Math, and a number of other system objects based on their value -- that's why this if appended to the previous CODE works:

    alert(pet.name.toUpperCase());
    Code (markup):
    toUpperCase is a method of String.prototype -- which a variable holding a string automatically inherits; so it's an object.

    As such...
    function getPet() {
    	return {
    		name : 'Maddy',
    		gender : 'cat',
    		sex : 'female',
    		age : 10
    	};
    }
    
    var pet = getPet();
    Code (markup):
    Will make that version of "pet" identical to that first example of "pet" above once it's done running.

    Basically anyplace you can use a variable, you can use an object declaration... and that includes doing a return on a "literal object".

    This site is a little dated and has accessibility failings, but does a halfway decent job of explaining the different methods of creating and initializing objects.
    http://www.javascriptkit.com/javatutors/oopjs.shtml

    Hope that clarifies things.
     
    deathshadow, Mar 15, 2015 IP
  3. serialentre

    serialentre Member

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    30
    #23
    Ah yes, it clarified things for me! Thank you!

    Interesting to know that variables are objects too. Must have been confusing for people to learn Javascript!

    Thanks for the link too, pretty good!

    I'm actually learning JS to pick up Angualr js framework!
     
    serialentre, Mar 15, 2015 IP
  4. imbrod

    imbrod Well-Known Member

    Messages:
    212
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #24
    About those SEAF that Deathshadow mentioned, I've read those are also called IIFE - Immediately Invoked Function Expression (pronounced "iffy") whether they are anonimous or not. e.g. var f1 = (function() {}());
     
    imbrod, Mar 17, 2015 IP
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #25
    1) that's still anonymous, it's just evaluating and destroyed.

    2) ... and that's part of what is so annoying about this use of the word "closure" and JavaScript in general. There are a dozen or more different names for every single way of doing things, as it's a mish-mash of different programming backgrounds and it seems like every blasted year you hear a new term for an old thing. From resurrecting old-misuse of words for things they don't mean that should have gone the way of the dodo when Big Iron died that only LISP-tards and comp sci majors ever heard of in their theoretical zero real world application schooling, to new kid BS where they just pull a term out of their ass because they don't know the right one... It's getting pretty annoying.

    Though a lot of it is just background; See how if you learned objects in a PROPER environment like Smalltalk or Modula 2/Oberon when you get to C++ you go "what idiot pissed on object implementation" and by the time you get to PHP or JS it's "no typecasting? REALLY? Oh, that's going to be efficient, NOT!".

    See how when I learned Smalltalk what this thread is about weren't called "closures", they were called Hobbits, elves and dwarves depending on their scope -- something I've not found anywhere except the original book by Adele Goldberg. The Apple Object Pascal book for the LISA and early Mac referred to any extension of an object as an "ELF", If I used those terms today it would confuse the **** out of people... ELF in particular since people would think we were talking about realtime loading extensible object binaries into Linsux.
     
    deathshadow, Mar 19, 2015 IP
  6. imbrod

    imbrod Well-Known Member

    Messages:
    212
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #26
    It's just that term IIFE is considered to be more accurate (not my idea, I've read it on few sites), because the function is not self-invoked as in recursive, it is rather invoked by the program flow.
     
    imbrod, Mar 23, 2015 IP