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. #1
    Hi all,

    I am trying to wrap my head around javascript closure. I have seen a few examples and read up on a few tutorials.

    This is one of the better ones I've read.

    http://www.sitepoint.com/javascript-closures-demystified/

    Are there any practical examples that I can learn from?

    Thanks!
     
    serialentre, Mar 8, 2015 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #2
    Ok, that page seems to be filled with bullshit new terms for EXISTING methodologies that already have other names. What's being done there is simply having the function return an anonymous function -- which depending on how often that's called could be a disastrous waste of memory. (that does NOT mean "don't ever use anonymous functions")

    I'm sitting here thinking "WTF is the big deal about }", since in C syntax languages } is a "closure".

    NONE of the terms on that page are used for anything they mean -- I would half suspect the author of pulling names for things out of their backside. What the hell is it lately with people slapping new names on two decade old methodologies?

    Of course, it's on SitePoint so it being full of **** isn't exactly a surprise. Those are the same jackasses who claim that omitting metrics on line-height "works problem free" even when you show it broken with instructions on how to break it, and release books about "JavaScript" that don't teach the first damned thing about the underlying language and amount to little more than "use jQuery"

    What they are doing there is returning an anonymous function as the result of a function *YAWN*. What the hell that has to do with "closure" is beyond me, and I've been writing software for well over three decades.
     
    deathshadow, Mar 12, 2015 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    I don't get it either - is "closures" in Javascript any different from containing functions etc. in other languages? I understand that a "function within a function" can access variables set in the outer function in Javascript, but... how / why is that defined as a "closure"?
     
    PoPSiCLe, Mar 12, 2015 IP
  4. serialentre

    serialentre Member

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    30
    #4
    Oh man. I would have thought the author's explanation was correct and proper!

    Thanks for pointing it out!

    Are there places online or books that I can refer to for official documentation or explanation of javascript? I understand, though, there's no official documentation because every browser has their own javascript standards.
     
    Last edited: Mar 12, 2015
    serialentre, Mar 12, 2015 IP
  5. PDD

    PDD Greenhorn

    Messages:
    67
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    23
    #5
    Technically that is a closure. The one he showed there is called a "continuation" and is pretty much rigidly defined as a closure. There's some more info here: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work/111200#111200
    or if you're hardcore then go straight for the specification
    http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
     
    PDD, Mar 12, 2015 IP
  6. ketting00

    ketting00 Well-Known Member

    Messages:
    772
    Likes Received:
    27
    Best Answers:
    3
    Trophy Points:
    128
    #6
    Closure has been discussed pretty much in high performance JavaScript forums. If you interest, I suggest to begin with prototype and class. In this case, Google is your best friend.
    Just for example, considering this:
    
    function log( msg ) { document.getElementById('log').innerHTML += msg + "<br/>"; }
    
    function myFunction( y ) {
        this.y = y;
        log( this.y );
    }
    
    for ( var i = 0; i < 1000; ++i ) {
        var xo = Math.random(),
           ox = new myFunction( xo );
    }
    
    Code (markup):
    VS
    
    var somePrototype = {
        a: function ( y ) {
            this.x = y;
        },
        b: function() {
            document.getElementById('log').innerHTML += this.x + "<br/>";
        }
    };
    
    function myFunction( y ) {
        function F() {};
        F.prototype = somePrototype;
    
        var f = new F();
    
        f.a( y );
        return f;
    }
    
    for ( var i = 0; i < 1000; i += 1 ) {
        var xo = Math.random(),
           ox = myFunction( xo );
               ox.b();
    }
    
    Code (markup):
    They do pretty much the same thing and you didn't even notice the difference.

    But, which one do you think is the better method. Use Chrome dev tool to inspect it.
     
    ketting00, Mar 13, 2015 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    Uhm... Neither? Both piss all over the global namespace, repeat a painfully slow operation over and over, and suck on RAM like candy creating endless pointless "objects for NOTHING" that by all appearances aren't even released properly, and use innerHTML in the traditional "Let's force a reflow of the whole page" manner. Only someone who knows NOTHING about objects would write code like that.

    ... and that's not "closures", that's SCOPE? Whiskey Tango Foxtrot is being "closed"?!?

    In pretty much 90%+ of programming languages, a CLOSURE is something like }, ] and ). In Pascal "end" is a closure... technically a trailing single or double quote on a string is a closure. In SGML/XML/HTML/XHTML the > on part of a tag is a closure, as is a closing tag like </html> or the /> in XML/XHTML... in a dictionary, well...

    1. the act of closing; the state of being closed.
    2. a bringing to an end; conclusion.
    3. something that closes or shuts.
    4. an odd shaped brick or tile at the edge of a layout used to fill gaps
    5. an architectural screen or parapet, especially one standing free between columns or piers.
    6. Phonetics. an occlusion of the vocal tract as an articulatory feature of a particular speech sound.
    7. Parliamentary Procedure. a cloture.

    The only word that even comes CLOSE to what that is, limitation of and inheritance of scope, would be an ENclosure, as the scope of the local values are ENCLOSED.

    Seriously, EVERY code example I'm finding from the scripttards are laundry lists of how NOT to do whatever the hell it is they are trying to do -- pissing away memory and speed in the process. In BOTH cases they're handing off **** that doesn't need to be handed off and creating extra copies and releases for NOTHING of value.

    Since XO is immediately discarded, why is it created, why store "this", why store values in "this", why getelementByID every blasted time... There is no reason to be discarding and creating the same object over and over and over again other than "I cans haz intarnets" coding ignorance. Variables for nothing, instances for nothing; there's nothing quite like making memory thash and chewing on the CPU for a bunch of things that should only be done ONCE.

    var vLog = {
    	DIVLog : document.getElementById('log'),
    	add : function(value) {
    		this.DIVLog.appendChild(document.createTextNode(value));
    		this.DIVLog.appendChild(document.createElement('br'));
    	}
    }; // vLog
    
    for (var i = 0; i < 1000; i++) vLog.add(Math.random());
    Code (markup):
    ... and in ANY of these cases what the blue blazes any of that has to do with what "closures" are in programming languages is beyond me. Foxtrot scripttards man... and that PDF sure as shine-ola doesn't make it any clearer since they just seem to throw the word in willy-nilly as if some other word was meant to be used, but they screwed up translating it to English after taking it from Japanese to Norwegian first.

    But considering that most likely said document was made by the same types of jackasses who used the word "EMPTY" in the HTML specification not to mean an element without content, but an element that LACKS content, and used the word "deprecated" instead of "depreciated" I probably shouldn't be surprised. Last time I checked we weren't talking down to those older tags like a dog that just **** on the carpet or doing the "I'm a retard" voice halwtis do talking to anyone under the age of 7... that when I was a kid would have gotten you a slap.

    What the blue blazes language is that train wreck even written in, 'cause it sure as shine-ola isn't English; or at least sure as spit didn't start out in English.

    Scripttards -- I swear sometimes I just want to line the whole lot up against a APC to recreate the scene from Red Dawn. NONE of this makes the least bit of sense to even be using the WORD "closure"; and as I said before reeks of some jackass just making up terms for something that already existed out of ignorance of the language in use. (in this case, English).
     
    Last edited: Mar 13, 2015
    deathshadow, Mar 13, 2015 IP
    PoPSiCLe likes this.
  8. PDD

    PDD Greenhorn

    Messages:
    67
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    23
    #8
    I don't know what you're on about man. Closures have been a paradigm in functional programming for decades. The application of functional programming to procedural programming is what propagated the term "closure". It's a well known and applied paradigm that's been refined over and over and utilized over and over. I don't know why you're taking a dictionary definition and arguing about what they should be called. Why is a method in java not called a function? Why do people denote constants in javascript with "var" when it's not variable? Why don't some strictly typed languages support final declarations? You can go on and on about semantics, but in this case you're arguing about a well defined word that's been used forever to describe scope of inner subroutines. Read here:

    http://en.wikipedia.org/wiki/Closure_%28computer_programming%29

    I don't get why you're so hostile either. Just because you've been programming for 30 years or whatever doesn't mean your opinion is automatically the correct one. No one cares about your opinion about whether it should be called a closure or not, that's what it's called and has been called for years.
     
    PDD, Mar 13, 2015 IP
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #9
    HOW did I know that word was going to crop up...


    I really didn't last long as part of a writing staff...

    Interesting, I didn't know there was a distinction other than the late 90's revisionism where suddenly passing a reference to a procedure magically became "functional programming" -- which was college teacher BS used to pad out the coursework for no good reason other than to take something simple and MAKE it hard.

    Apparently not THAT well known since the wikipedia article you linked to has "citation needed" on pretty much every claim.

    Yes, let's just ignore what the WORD MEANS... RIGHT.

    Because it's also a property of the object and can be instanced more than once with a different scope; it's not as simple as a machine language CALL/RET?

    Though I'm a smalltalk / object pascal / modula guy, so to me a method, function and procedure are three separate things.

    Uhm... JavaScript doesn't HAVE constants?

    Unless they aren't compiled, they wouldn't need to; that's a security method for half-assed object models like PHP's.

    Interesting that "well defined word" has nothing to do with the word's definition... or that it seems to magically be needed to explain scope and inheritance. Isn't that EXACTLY the type of crap that Wirth, Kernighan and Ritchie were trying to put a stop to? Admittedly, I'm a "Wirth kind of guy"

    ... oh I don't know, possibly because EVERY code example I'm seeing would have gotten me a whap across the knuckles by a nun for being bad coding practices? That this idiotic halfwit nonsense and the code it vomits up is taking the simplest of tasks and pissing all over the code actively encouraging people to sleaze out some of the DUMBEST methodologies I've seen in my time? Hell this **** makes idiotic mouth breathing dumbass halfwit nonsense like jQuery, Bootcrap and Turdpress look good!!!

    It reeks of the same "college professor busywork" that just confuses people starting out, gives them a sick buzzword to lord over others with, and takes the simplest of tasks and makes it needlessly and pointlessly complex. Kind of like what Wirth said about programming in general; "It's like some people out there are intentionally trying to make programming hard. It isn't; or at least it shouldn't be."

    Programming is simple, STOP MAKING IT HARD with abusing words for what they don't even mean, needlessly convoluted and ultimately pointless "paradigms" that do nothing but generate code bloat and piss all over memory allocation and execution times, and make the resultant code a thousand times harder for anyone to comprehend!

    It's almost as bad as the idiocy of shoe-horning MVC into non-event driven languages like PHP.

    Type of thing I'd expect back-room server unix geeks from the early 80's to be circle jerking each-other over because they were still getting paid by the K-LoC. Kind of like how today nobody seems to see what's wrong with using 500k of minified .js to do 15-20k of uncompressed scripting's job or things that have no damned business being done in scripting in the first place.

    Though the part making me REALLY "hostile" about it is that poor sods like @serialentre encounter this type of pointless nonsense leading nubes down the garden path to failure, or frustrates them right out of even trying. It's why with all the bad practices, sloppy coding and outright BS being propagated as "good practices" I pity ANYONE trying to learn programming right now as they are having more smoke blown up their backside than a drowning man on the Thames.

    ... and why my disgust with the industry as a whole has blossomed from disgust to the point of nausea into full on projectile vomiting Linda Blair style.
     
    Last edited: Mar 13, 2015
    deathshadow, Mar 13, 2015 IP
  10. PDD

    PDD Greenhorn

    Messages:
    67
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    23
    #10
    Honestly almost everything you said there was nonsense. You just try to be angrier than the person you're arguing with and hope they back off. I don't care much for this argument and this will probably be my last post in this thread, but here goes:
    http://en.wikipedia.org/wiki/Lisp_%28programming_language%29
    Note: Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today
    There's 3 [citation needed]'s in that entire document. And it has 17 references. I don't understand what your point was here, other than to make yourself look dumb.

    As clearly you have very little understanding about linguistics or evolution of language, you can take a read here:
    http://www.ling.upenn.edu/courses/Fall_2003/ling001/language_change.html
    Most notably the second paragraph if you don't care to read the entire thing. Language changes. I again don't understand your view here. You just want to argue semantics for some apparent reason. Again, no one cares.

    Same with PHP, same with C++, same with C. What's your point? By the way, it's more apt to call it a member than a property but I'll let it slide.

    That's my point. Why aren't you torn up about the fact that it doesn't have a semantic representation of a constant?


    I guess C++ is a half assed language too. Note: const keyword. Purists use it.

    Actually, "well defined" has everything to do with a word's definition. If we go back to the linguistics 001 lesson we see that language changes. The definitions of words change, depending how we use them. It doesn't need to explain scope or inheritance, in fact I'm starting to question whether you even understand the premise of a closure.

    Spoken like a man without an education. It's fine to be uneducated, but please don't argue with people who know what they're talking about. You look stupid.

    Programming isn't simple. Maybe the programming you do is. But sometimes exotic structures and forms of invocation are required to deal with complex code in an elegant way. At this point I'd honestly like to see some of the code you've produced. Like the most complex code that you've done. It seems that you're set in your ways, surprised you even know what javascript is and don't have the old vb6 kicking around still.

    I don't know why you keep bringing up PHP, but several other non-event driven languages employ MVC for the web and ui constructs. It's a good practise and allows for clean design, regardless of whether the underlying language is fundamentally event driven or not.
     
    PDD, Mar 13, 2015 IP
  11. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #11
    Then you have a different viewpoint on programming than I do. There's "theoretical BS" and "practical application" -- and a LOT of the theoretical BS is just plain bad advice that leads to bad, bloated, and difficult to maintain code.

    No, I'm just a New Englander. We are not a friendly people. :D We also have a different definition of humor; seems like what we consider funny and normal others get their panties in a knot over... as our friends in Brooklyn might say, "Ya gaht a freakin' problem wit dat?"

    "Evolution of language" is one thing, using a word for something it doesn't mean just confuses people; you end up with the situation of Samuel L. Jackson having the difference between bollocks and dog's bollocks needing explanation. Not bad meaning bad but bad meaning good...

    C doesn't have objects, and as such has no methods... not sure what you were aiming for with that.

    Depends on if you learned objects in smalltalk, OP or ADA vs. C++.

    Semantic shmantic, it's not the representation, it's the IMPLEMENTATION -- and YES, it does suck that JavaScript utterly and completely lacks constants. Or if you prefer, DEFINE... Some Pascal implementations are similarly hobbled in that their "constants" are actually variables as well that the compiler doesn't let you access directly, but that you can still change with pointers. (and hence means no constant folding at the compile stage).

    C++ IS a half assed object implementation -- at least if you did something like learn objects in smalltalk or ADA first. Yes, I said ADA... The tinfoil hat crowd will now avoid this thread as they'll think alphabet soup is listening.

    IF I'm following what these articles are claiming it is, it's just the limitation of scope within a namespace like a function. *YAWN* that needs explanation and a term?!?

    I actually just took a page from Clemens: I never let education get in the way of my learning; a hefty chunk of why I have zero respect for the majority of "professional educators" most of whom don't have enough knowledge of the topic they allegedly teach to be educating a single soul on ANYTHING. Goes hand in hand with my considering a degree in IT to be worth less than a sheet of bog roll.

    Programming IS simple; but to keep that in perspective I STILL would rather hand assemble 8k of Z80 machine language than deal with 100 lines of needlessly complex, convoluted and cryptic C code. I'm STILL not convinced that this is a joke:
    https://www.gnu.org/fun/jokes/unix-hoax.html

    A lesson I had drilled into me early is that "the more code you use, the less there is to break." -- which goes hand in hand with the simple fact that clear, clean, simple, verbose code is easier to maintain and far less prone to failure. "exotic structures and forms of invocation" to me is needless complexity that is anything BUT elegant... Which is why on most tasks I use a third the code most people seem to vomit up and call a program these days.

    Hmm... most complex... Generally I don't do complex, I take the complex and MAKE it simple. In fact that sums up my programming career is going around and taking codebases and reducing them 50% or more. It's what I did in DiBol in the 80's, In C and Pascal in the '90's, in HTML in the '00's, and in PHP and JS over the past decade or so.

    But... how about a bitmap decoder specific to a certain data stream for the 8088?
    ; procedure mapToBackBuffer(colorSet:word);
    pProcArgs mapToBackBuffer
    	mov  di, backBuffer
    	mov  ax, ds
    	mov  es, ax
    	call  selectColorSet ; set bx as offset to palette
    	                     ; also clears CX and points SI at mapLineList
    .nextLine:
    	lodsw
    	or   ax, ax
    	jz  .done
    	mov  dx, si
    .flipSI_nextByte:
    	xor  si, si
    	xchg si, ax
    .nextByte:
    	lodsb
    .xxxx_xxx?:
    	shr  al, 1
    	jc   .xxxx_xx?1
    .xxxx_xxx0:
    	add  di, ax
    	jmp  .nextByte
    .xxxx_xx?1:
    	shr  al, 1
    	jc   .xxxx_x?11
    .xxxx_xx01: ; repeat LL
    	mov  cl, al
    	mov  al, [bx + 11]
    	rep  stosb
    	jmp  .nextByte
    .xxxx_x?11:
    	shr  al, 1
    	jc   .xxxx_?111
    .xxxx_x011: ; repeat HH
    	mov  cl, al
    	mov  al, [bx + 12]
    	rep  stosb
    	jmp  .nextByte
    .xxxx_?111:
    	shr  al, 1
    	jc   .xxx?_1111
    .xxxx_0111:
    	xlat
    	stosb
    	jmp  .nextByte
    .xxx?_1111:
    	shr  al, 1
    	jc   .xx?1_1111
    .xxx0_1111: ; EOS
    	add  di, 6
    	mov  si, dx
    	jmp  .nextLine
    .xx?1_1111:
    	shr  al, 1
    	jc  .x?11_1111
    .xx01_1111:
    	; sadly it's faster to do these separate than it is to preserve AH
    	mov  al, [bx + 1]
    	stosb
    	mov  al, [bx]
    	stosb
    	jmp  .nextByte
    .x?11_1111:
    	shr  al, 1
    	jc   .?111_1111
    .x011_1111:
    	mov  al, [bx]
    	stosb
    	mov  al, [bx + 1]
    	stosb
    	jmp  .nextByte
    .?111_1111:
    	lea  ax, [bx + 6]
    	xchg  si, ax
    	movsw
    	movsw
    	jmp  .flipSI_nextByte
    .done:
    	pRet 2
    Code (markup):
    That's about as complex as I've ever gotten. For anything contemporary 'complex' isn't even in the vocabulary, because I look at 99%+ of the code people vomit up and go "What the **** are you doing? That's 50 lines of code for what I can do in five!"

    Good laugh considering I hate BASIC... was a cute toy when it was 8-12k in ROM that you booted into, but the moment you needed to write anything serious you looked somewhere else; that it continues to lumber on to this day is a bit surprising.

    ... though I do have a mental block that prevents me from learning "visual" programming, and find most "IDE's" to be more work, not less; kind of like the illegible acid trip of syntax highlighting and all the other rubbish "tools" that are at best crutches, at worst encourage mistakes instead of teaching habits to prevent them. Makes me wonder just what the devil modern programmers are smoking with all this crap that makes them work harder that they have somehow been convinced is magically "easier"

    Because writing more code is "easier", using more complex tools that make code management HARDER is "easier"... makes me go all Inigo on the current crowd of sleazeball halfwits and their nube-predating BS.

    ... and they are ALL bloated, slow, and an incorrect "paradigm" for the environment. It's taking a 500 pound fat woman's size 17 hoof and shoe-horning it into a size 6. It is a BAD practice for something that is as simple as linear IPO. (input, process, output).

    I DO see the merits of separating things like processing from output; the thing MVC provides in environments where UI api's like GTK or DWM -- but the MVC model outside a non-linear non-event driven environment is just silly... and code bloat.... and is why we're seeing the same type of code wasting time wasting framework nonsense server-side that we're seeing piss on websites from orbit client-side! (again, see 99.99% of the crap people sleaze onto websites with jQuery that is either CSS' job or has no damned business on a website in the first place)

    User makes the request, you process the request and gather the data, then you send the data to the output. HOW HARD IS THAT? But no, we have to do this convoluted endless pointless object model train wreck with more entry vectors than the common cold -- who cares how much the stack is thrashing, how many endless pointless calls or made or how much it sucks on memory like a horde of kindergarteners set loose at a tootsie pop factory! I know, we'll just throw more hardware and more code at it as that ALWAYS fixes everything...
     
    Last edited: Mar 13, 2015
    deathshadow, Mar 13, 2015 IP
  12. PDD

    PDD Greenhorn

    Messages:
    67
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    23
    #12
    i was referring to function pointers in C's case

    I mean, you're showing some assembly code for some old ass chip as the most complex code you've written. I respect the grind of it, but that's not complex. And I think that your lack of necessity for these paradigms is the reason you have your opinions. Try to do some latent semantic analysis with your favored functional programming language and I think you'd quickly change your opinion.

    We would never agree on MVC because you plainly have an old fashioned and frankly, obsolete opinion on what good design is. It's much, much simpler to arrive at a maintained MVC codebase than some functional shit where I need to use debuggers constantly to figure out what's going on in it.

    And about your points about complexity. There's really not much we can agree on there either unless you're talking about algorithmic complexity. Because all the "complex" structures that you refuse to learn are there for a reason. It's to abstract the tedious operations that someone like you would rewrite in every single application they write. It's a matter of efficiency and also those designs are almost always designed in the most optimal way with careful planning. I really dislike the mentality of "back in my day...".. it's like okay well we're not in your day and it's not my problem you can't keep up anymore.
     
    PDD, Mar 13, 2015 IP
  13. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #13
    @PDD I would perhaps simmer down a bit. I dunno about @deathshadow and compiled languages, but I wouldn't scoff at his more efficient code. He made a js-"framework" last year (what happened to that project?) for one. The point is, I tend to agree with @deathshadow, in most code-related issues. And frankly, while MVC has its merits, it's for instance completely useless in PHP, for one, as it adds unnecessary bloat.
     
    PoPSiCLe, Mar 13, 2015 IP
  14. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #14
    The site is still there, but I'm probably killing it before it actually turns into a "framework". Simple fact is that most of what it does I wouldn't do on a website in the first damned place. It's cute for solving a few minor redundancies and filling implementation gaps, but stripping the functions out to be procedural and just including the ones I might actually use ends up being what I deploy.

    I'm pretty much fed up with scripttardery as a whole since again, good scripting should enhance functionality, NOT replace it... and the way people are pissing away bandwidth, handshakes, and functionality by throwing scripting at everything for no damned good reason, I'm not sure I actually want to encourage the practice... and that "disgust to the point of nausea with the industry as a whole" I keep mentioning being a hefty chunk of why that project has been left to rot for a few months.

    Though I also soured on it when a friend offered to help and buggered several sections resulting me introducing boots to backsides -- so now I've got to go back through and fix it again and since I'm NOT actually using it for anything, I'm not sure I'll even bother and I'll likely just bury it as a bad idea.

    Well, along with the whole failing health / borderline bedridden / stay in the ICU thing...
     
    deathshadow, Mar 13, 2015 IP
  15. ketting00

    ketting00 Well-Known Member

    Messages:
    772
    Likes Received:
    27
    Best Answers:
    3
    Trophy Points:
    128
    #15
    I'm not talking about closure man. I'm not understand anything about it.

    I run the test to compare codes above. Some times the second method I use wins. Some times @deathshadow wins, but he wins more count. There is no conclusion for this.
    I ditch something like this some times ago. Creating element and append. Actually it should be done with array.

    Why you use [this]. I heard [this] makes confusion.
     
    ketting00, Mar 13, 2015 IP
  16. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #16
    Yes, because artsty fartsy BS mated to the worst of 1990's scripttardery is the bleeding edge of accessible design; why is it the more tools and instructions we are given for doing things cleanly, simply, easily and in a manner that's more useful to the end user people insist on pissing on it from orbit?

    Since apparently clean minimalistic code, simplicity, and accessibility are all "old fashioned and obsolete". RIGHT...

    Of course, if you "Constantly need debuggers" to figure out what's going on, you've made whatever you are doing more complex than it needs to be.

    Oh, and...
    You say that almost like you think I'm saying objects are bad; I have a problem with "objects for nothing", I have a problem with "endless pointers for nothing" and "brute force where brute force isn't needed" -- that doesn't mean I'm going to "favor functional programming".

    Makes me wonder if you know what Smalltalk, Object Pascal and Modula are.

    I do so love how many programmers seem to think that functional and object programming thinking needs to be two entirely separate realms that never mix. Probably why I'm also not a fan of Java -- well that and the fact that on any non-android system I've ever installed it on you're looking at virus/malware city inside a 24 hours if you don't disable browser access to it...

    Though my approach to SVD usually pisses off "computer science" types as I do it using integers; but then I'm the same guy who in 3d math uses vector math and arctangents for translations, rotations and final projections instead of matrixes and Z-Divides, so...

    That said, LSA still lacks a lot in terms of normal practical application and can be grossly inefficient compared to even brute force searches and conventional indexing, even if the results are better. A lot of that comes down to how good a dictionary of synonyms can you start with before feeding it things to compare; Without that it's like knowing the syntax but not the words.

    You are right, complexity for doing complex tasks is fine; what I'm bitching about is people using complexity for the simplest of tasks -- which is just stupid and why most frameworks be they JavaScript or PHP are just idiotic dumbass garbage that again, is usually either CSS' job or doesn't belong on a website in the first place -- or worse, has to be done AGAIN server-side since you can't trust anything client-side.
     
    deathshadow, Mar 13, 2015 IP
  17. serialentre

    serialentre Member

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    30
    #17
    wow. that's alot to digest, most of which I don't quite understand.

    My purpose of asking the original question is to understand javascript fundamentals. When I read online tutorials, it doesn't explain the in-between steps, and worst - The authors use highly technical words and sometimes don't explain it.

    Back to the question though, where can i find good resources to learn javascript properly?

    Basically, I am googling for answers, without really knowing if pple are explaining it correctly.

    These two are pretty good -
    http://javascriptissexy.com/understand-javascript-closures-with-ease/
    http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

    What do you all think about what is mentioned by the author?

    Thanks again!
     
    Last edited: Mar 13, 2015
    serialentre, Mar 13, 2015 IP
  18. serialentre

    serialentre Member

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    30
    #18
    This is pretty confusing for me.

    The author returned some properties within a function. Is that the proper way of creating methods in a function?

        function celebrityID () {
        var celebrityID = 999;
        // We are returning an object with some inner functions
        // All the inner functions have access to the outer function's variables
        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;
            }
        }
    }
    var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.
    mjID.getID(); // 999
    mjID.setID(567); // Changes the outer function's variable
    mjID.getID(); // 567: It returns the updated celebrityId variable

    Code (markup):
     
    serialentre, Mar 13, 2015 IP
  19. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #19
    That's just abusive and grossly inefficient use of scope; aka memory wasting BS done JUST as an example... one would HOPE that nobody would ever ACTUALLY write code that way.

    Basically in Javascript when you open a function any variables created when the function is called are preserved. ALWAYS. (horrible memory wasting crap as stuff is rarely removed, which is why deep doo-doo scripttardery leaks memory like a steel sieve under Niagra falls)

    What's going on there is pretty simple (even if it is a dumbass way of doing things). The VAR declaration in the outer function creates a "variable" that's local in scope to that function. I put variable in quotes as it's not just a variable, it's also a property of the function, as all JavaScript functions are actually objects.

    Let me say that again, ALL JavaScript functions are actually objects. Variables declared inside them with VAR are basically the same as a private property, while variables declared with this.varname are basically public.

    JavaScript has no "down-scope" protection, so anything declared inside that function/object SHOULD have access to any VAR or "this" properties. The function itself returns a new object who's methods are able to also access the parent object's scope. Laughably your last example would NOT work, all those getID would ALWAYS return 999. (check it!)

    Which is why JS is considered a "loose scope" language and has all the security and efficiency of line numbered basic from the 1980's; but it's an interpreted language, that's usually par for the course.

    Really the part I think you are missing is that all JavaScript functions are also objects.

    function myFunction() {}
    is an object.

    var myFunction = function() {}
    is an object

    var myFunction = {}
    is an object... without a constructor.

    ... and of course lacking proper classes/struct/records/whateverTheLanguageYouAreUsingThisWeekWantsToCallThem that an turn into a confusing memory wasting mess REALLY quick. PARTICULARLY if garbage collection takes too long to trip or fails, which is one of the reason scripting-heavy websites often send firefuxxors off to never-never land. Google's V8 engine on the other hand has excellent garbage collection.
     
    Last edited: Mar 14, 2015
    deathshadow, Mar 14, 2015 IP
  20. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #20
    Actually, looking at all these "examples" I'm seeing another reason you might be having difficulty following them, and it's why they piss me off as "what's the point" and "who the **** would write code this way" -- NONE of them actually do anything you would actually do in real code so far as examples go. It's another example of "false simplicity" -- the examples have been dumbed down so far, you no longer see the real world application for it... they just magically expect you to pull that part out of your ass. (You'd almost think career educators and CompSci types were involved)

    Let's use that most recent example as a template, but follow it up with a "real world" usage scenario. The missing part of the equation is doing something MORE with the setter than just setting the value to whatever is passed. If you're just passing the value to set, why not just use a flat variable? You add something like say... validation to it, suddenly that construct will make sense. Let's say we only want to allow the value to be set as a range of 300 to 1299. I will retain their memory wasting construction for this.

    function celebrityID () {
    	var id = 999;
    
    	return {
    		getID: function() {
    			return id;
    		},
    		setID: function(newID) {
    			 return (
    				(newID > 299) && (newID < 1300) ?
    				(id = newID) :
    				false
    			);
    		}
    	}
    }
    
    var mjID = celebrityID();
    alert(     'getId: ' + mjID.getID());    // 999
    alert('setID(567): ' + mjID.setID(567)); // 567
    alert(     'getId: ' + mjID.getID());    // 567
    alert(  'setID(0): ' + mjID.setID(0));   // FALSE
    alert(     'getId: ' + mjID.getID());    // still 567
    
    Code (markup):
    The returned new object retains access to the creating object's properties and methods. Adding a simple range validation and value/===false return shows how such a construct could be useful. It is impossible to set celebrityID{id} directly -- the entire reason to be using a setter and getter in the first place.

    Depending on how many instances of that you create, returning an ... I guess one would call it an "anonymous object' can become really wasteful of memory, a better approach would be:

    function celebrityID () {
    	var id = 999;
    
    	this.getID = function() {
    		return id;
    	};
    	this.setID = function(newID) {
    		 return (
    			(newID > 299) && (newID < 1300) ?
    			(id = newID) :
    			false
    		);
    	};
    }
    
    var mjID = new celebrityID();
    alert(     'getId: ' + mjID.getID());    // 999
    alert('setID(567): ' + mjID.setID(567)); // 567
    alert(     'getId: ' + mjID.getID());    // 567
    alert(  'setID(0): ' + mjID.setID(0));   // FALSE
    alert(     'getId: ' + mjID.getID());    // still 567
    Code (markup):
    Being a VAR not a 'this' you don't have access to it outside the object, and making a new instance of an existing object prevents code redundancy sucking on RAM. (at least in engines other than Google V8 -- V8 is actually optimized to let crappy code run well...)

    A more practical example to show why returning ===false from the setter would go something like:

    while (
    	mjID.setID(prompt('Enter a number 300..1299')) === false
    ) alert('Invalid Value, please try again!');
    Code (markup):
    That's a bit rough (real code should also check the value is actually a number), but should give you an idea what I mean.

    Did that help clarify what's going on at all?
     
    deathshadow, Mar 14, 2015 IP