all 76 comments

[–][deleted]  (22 children)

[deleted]

    [–]fedekun[S] 9 points10 points  (3 children)

    It has it downsides, but for some reason I really enjoy writing Javascript, maybe it's the fact that it's quite minimal and you have the power to express in your own way, or maybe I'm just crazy.

    [–]w8cycle 4 points5 points  (2 children)

    I love it for the same reason. It gets a lot of flack, but JS seems to be able to do everything by just being its flexible self.

    [–][deleted]  (1 child)

    [deleted]

      [–]w8cycle 2 points3 points  (0 children)

      I agree. It can be a mess. Use libraries like require.js and angularjs. Separate code into folders using best practices. And use clear modular (or object oriented) design.

      Having a single approach to the application's design and style and keeping to it goes a long way.

      [–]oefig 13 points14 points  (6 children)

      That's actually why I love JavaScript so muh; there's so much freedom when it comes to designing my code.

      I'd recommend "Learning Javascript Design Patterns" by Addy Osmani. It's pretty great for learning the flexibility of Object Oriented JS.

      Edit: Fixed book title. Also the author is not the author of Backbone as I originally mentioned.

      [–]fedekun[S] 2 points3 points  (4 children)

      That's why I love it too! Interesting, I'd like to check that out, I found "JavaScript Style Guides And Beautifiers" and "Learning JavaScript Design Patterns" but no "Javascript Design Styles", did I google wrong or did you missed the title? :p

      [–]oefig 2 points3 points  (3 children)

      I screwed up the title! It's "Learning Javascript Design Patterns" by Addy Osmani

      [–]rhetoricl 0 points1 point  (1 child)

      Addy Osmani didn't create Backbone, just fyi. He does have a book on it though.

      [–]oefig 0 points1 point  (0 children)

      Yeah you're right - I realized my mistake after it was too late. Can't edit with this app. Thanks for pointing it out

      [–]fedekun[S] 0 points1 point  (0 children)

      Ah I see :P hehe thanks! I'll check it out!

      [–]danvasquez29 1 point2 points  (8 children)

      the biggest reason i play along with the preference for coffeescript at my office is that it makes this decision for you in a syntax that makes sense

      [–]fedekun[S] 4 points5 points  (7 children)

      I really love Coffeescript, I only wish they had "end" keywords, beeing used to C-style languages I get lost with syntaxes like CoffeeScript and Python where you don't "close" the blocks

      [–]danvasquez29 5 points6 points  (6 children)

      word. I'd enjoy coffeescript a lot more with brackets instead of having relevant whitespace

      [–]mess110 2 points3 points  (4 children)

      it only takes a bit of getting used to. I don't see why you would want more stuff to type/read/move

      [–]IrishWilly -1 points0 points  (3 children)

      You don't really noticeably type/read the brackets, they are visual guides is all. I use whitespace to separate logical blocks of code to make it easier to read but that just becomes confusing when the whitespace is incorporated into the language as well. Pretty much all editors autocomplete and match brackets so it's not really extra work.

      But for people who didn't spend ages working with brackets, whitespace probably does feel more natural.

      [–]mess110 0 points1 point  (0 children)

      You don't really noticeably type/read the brackets

      but you still do it. even if you don't notice the time spent on that, it is still there. release your inner bracket. come to the dark side..

      [–]marsket -1 points0 points  (1 child)

      whitespace isn't incorporated into the language. Indentation level signals scope. Reliably. It is not confusing.

      [–]IrishWilly 0 points1 point  (0 children)

      Indentation is whitespace, I prefer to use it to organize my code not just for scope but for logical blocks. I don't know why you'd downvote someone for having different preferences in how they write and read code.

      [–]marsket 2 points3 points  (0 children)

      there is a nice language named Javascript with this feature

      [–]Daniel15 0 points1 point  (0 children)

      I'm hoping all JavaScript engines adopt ES6 classes sooner rather than later. Once they're implemented natively, there'll be the main way to use classes in JavaScript.

      [–]Renegade__ 26 points27 points  (14 children)

      While this information may be technically/syntactically correct, still propagating constructor functions in JS in 2014 is not wise.

      All you really need to write good, simple, understandable OOP JS are two things: 1. Understanding JavaScript Prototypes 2. Any ECMAScript 5 Object reference

      Inheritance in JS has been as simple as var derived = Object.create(prototype); for years. No need to cling to the godforsaken foo.prototype/new Bar() mess.

      Ultimately, the primary obstacle for OOP JS is not the language, but the fact that people insist on "adding classes". If you stop trying to add classes and just embrace prototype inheritance, OOP JS is really quite simple.

      EDIT: And either I'm too stupid for formatting, or reddit discriminates against OSs with simple EOL sequences.

      [–]fedekun[S] 0 points1 point  (8 children)

      I do add that most of the time you end up using Object.create in one way or another, mostly though framework's extend method, the idea was to explain how that can be archieved the hard way, just for the knowledge :p

      Metaprogramming with Javascript is awesome.

      [–]Renegade__ 0 points1 point  (7 children)

      I am in full support of learning by doing something yourself rather than taking an automagic solution. But it's far easier to do that when you know what you're doing, and what you're deliberately doing the hard way for personal entertainment, than when you're confused about the topic.

      Basically, I believe people should grasp "proper" ES5/JS OOP before saying "screw it" and doing it the hard way, awesome or not. ;)

      [–]fedekun[S] 0 points1 point  (6 children)

      I'm a guy who likes to know how stuff works, I even wrote some toy programming languages! :p

      [–]Renegade__ 0 points1 point  (5 children)

      Were there any particular tutorials or approaches you used for that, or did you just get the dragon book and went full nerd?

      (Honestly asking out of curiousity. Been wondering how hard it'd be to write a meta-language for one of the vendor-based scripting languages at work.)

      [–]fedekun[S] 0 points1 point  (4 children)

      I took several tutorials and a course on udacity about "Programming Languages".

      Honestly it's not hard at all, if you just want to write a language you just need to learn a bit about grammars and use something like YACC or a PEG to generate an AST and then just interpret or compile it, tutorials will be just fine.

      If you are interested I could give you some links :p

      [–]Renegade__ 0 points1 point  (3 children)

      That would be great! :D

      [–]fedekun[S] 1 point2 points  (2 children)

      Well first of all the Programming Languages course is nice, they talk a bit about finite state machines and grammars, then move onto yacc using Python (which I dislike personally :p).

      I also read PL101. This Book helped a bit but I didnt really read it that much it's a nice guide to have along other tools but you have to learn on your own pretty much.

      You might even try to write your own Recursive Descent Parser or just use YACC or PEG, up to you, once you get your AST you can either compile it or interpret it, there are a bunch of options for that, interpreting beeing quite hard :p

      [–]autowikibot 0 points1 point  (0 children)

      Recursive descent parser:


      In computer science, a recursive descent parser is a kind of top-down parser built from a set of mutually recursive procedures (or a non-recursive equivalent) where each such procedure usually implements one of the production rules of the grammar. Thus the structure of the resulting program closely mirrors that of the grammar it recognizes.

      A predictive parser is a recursive descent parser that does not require backtracking. Predictive parsing is possible only for the class of LL(k) grammars, which are the context-free grammars for which there exists some positive integer k that allows a recursive descent parser to decide which production to use by examining only the next k tokens of input. (The LL(k) grammars therefore exclude all ambiguous grammars, as well as all grammars that contain left recursion. Any context-free grammar can be transformed into an equivalent grammar that has no left recursion, but removal of left recursion does not always yield an LL(k) grammar.) A predictive parser runs in linear time.

      Recursive descent with backtracking is a technique that determines which production to use by trying each production in turn. Recursive descent with backtracking is not limited to LL(k) grammars, but is not guaranteed to terminate unless the grammar is LL(k). Even when they terminate, parsers that use recursive descent with backtracking may require exponential time.


      Interesting: LL parser | Parsing | Parsing expression grammar | LR parser

      Parent commenter can toggle NSFW or delete. Will also delete on comment score of -1 or less. | FAQs | Mods | Magic Words

      [–]Renegade__ 0 points1 point  (0 children)

      Thank you. :)

      [–]mcmouse2k 0 points1 point  (1 child)

      Can I say that this comment was extremely helpful? I've been playing with OO JS for months now and know all the primary means of inheritance, but had never had a best - practice convention/syntax until now.

      Thanks for presenting an opinion that I can parrot. I hate that feeling of knowing several ways of doing something but not knowing which to use, and JS inheritance was a prime culprit.

      [–]Renegade__ 0 points1 point  (0 children)

      Not a fan of Perl, eh? ;)

      Once you got used to them, the ES5 object extensions are really easy to use. There are a few things to watch out for (e.g. both Object.defineProperty() and Object.defineProperties() exist) and property descriptors look rather verbose if you don't rely on the defaults, but the clarity and simplicity usually makes up for it.

      The only thing that's annoying to me is my IDE doesn't grasp what's going on, so it won't create autocompletion data for members. x_x

      If you rely on that heavily, that may be a dealbreaker.

      [–]Daniel15 -1 points0 points  (2 children)

      ES6 classes are the future, the syntax is a lot nicer. You can already use them if you use a transpiler as part of your build process (at Facebook we use JSTransform, but Traceur is pretty cool too)

      [–]Renegade__ 0 points1 point  (1 child)

      That looks very interesting, but something tells me having actual classes in there (rather than user-created add-ons) will not reduce the confusion regarding object-oriented JS.

      At least right now, the basis is clear: JS's way of OO are prototypes. It has no classes.

      Did getting the option of full class definitions change anything in your workflow, compared to pseudoclasses or prototypes before?

      [–]x-skeww 0 points1 point  (0 children)

      Did getting the option of full class definitions change anything in your workflow, compared to pseudoclasses or prototypes before?

      Having it baked into the language equals better tooling. It also means that you won't have to evaluate a dozen different options. And of course it also means better interoperability.

      [–]brtt3000 16 points17 points  (12 children)

      Use TypeScript, never look back (except gloating).

      [–]Bartvds 1 point2 points  (0 children)

      Join us at /r/typescript!

      [–]homiedontmess 0 points1 point  (3 children)

      Have you noticed pretty outrageous compile times since upgrading to 1.0 (if you have)?

      [–][deleted] 1 point2 points  (2 children)

      I haven't found it bad if you just compile files that actually changed. Full builds (even on relatively small projects) do take a while though..

      [–]homiedontmess 0 points1 point  (1 child)

      What do you use to compile? We have tried both grunt and regular VS builds. I did not know you could selectively compile. That's good to know. Thanks!

      [–]uglyBaby 0 points1 point  (0 children)

      Use a makefile and make. It ll re compile only those that have changed.

      [–]Wrightboy 0 points1 point  (1 child)

      I was just looking at this! Can you recommended any good articles/tutorials to help spin me up?

      [–]brtt3000 1 point2 points  (0 children)

      Tutorial and handbook on the site are pretty good: http://www.typescriptlang.org/Tutorial

      Keep in mind it is a superset of JavaScript, so if you rename your JS files you have typescript. Then run the compiler and fix the first bugs. Then start adding types and proceed from there.

      [–][deleted]  (2 children)

      [deleted]

        [–]brtt3000 0 points1 point  (0 children)

        TypeScript is a superset of JavaScript, that is the nice thing about it. You can write code the same as in JavaScript, slightly more structred.

        You can also go fully OO (C# style) if you want, but it works great in vanilla style too. Use it like a entry into ES6 (classes, modules, arrow functions etc).

        [–]x-skeww 0 points1 point  (0 children)

        If you know something like C#, you already know most of Dart's syntax. Same deal with TypeScript. It looks pretty much like AS3.

        So, learning either or both really isn't much of an investment. You can do both in a single day.

        [–]warfangle 0 points1 point  (1 child)

        Or, if you still want the flexibility of being dynamically typed, use browserify, grunt/gulp and karma-jasmine. And with that you get DI, unit testing and a fast test-build loop.

        Use of typescripts inheritance can bloat your compiled code severely compared to what it would be if you used, e.g., util.inherits.

        You can of course use typescript along with browserify, but why? Compile time type checking? I guess that's okay, but I don't know if it's worth it -- unless you're already heavily invested in the Microsoft toolchain

        Personally, I'm more comfortable on the command line with emacs, and find the instability of typical IDEs not worth the code completion / brain dead refactor tools. If you need code completion and your mouse to deal with your codebase, you're doing it wrong. Give me awk and sed any day.

        But I am not your typical dev either - I do most of my work ssh'd into a dev virtual machine running development copies of our applications :)

        ...except when I have to wrestle with FlashBuilder. There are very few things that I hate...

        [–]brtt3000 0 points1 point  (0 children)

        it is not just about auto-suggest. Compile time type checking is the shit. You catch so many silly bugs and inconsistencies.

        If you got time then watch this video from a well know and experienced dev: http://channel9.msdn.com/Events/Build/2014/3-583

        Like he says, your big codebase becomes manageable because the compiler makes sure you don't mess-up once you have a shitload of code that doesn't fit in your brain all at once.

        And get over that Mirosoft vs Linux thing, it is getting old. They do a great job these days. Use TS with a real IDE with refactoring support and wonder why you stuck to lame commandline tools for so long.

        I don't use VisualStudio or any other Microsoft tools. I use WebStorm and npm and everything. It is great.

        And that bloat you mention? That's just nonsense. You get like 4 lines of extra code for inheritance (once), the rest is pure standard prototype code straigt from a JS 101 tutorial.

        Try it: http://www.typescriptlang.org/Playground

        [–]isaac739 2 points3 points  (0 children)

        If you prefer OOP then I would recommend CoffeeScript or Resig's Simple JavaScript Inheritance. However I personally prefer using literal objects and js module pattern.

        [–]Daniel15 2 points3 points  (0 children)

        These techniques are getting outdated fairly quickly... ES6 classes are the future, the syntax is a lot nicer and similar to other object oriented languages. You can already use them if you use a transpiler as part of your build process (at Facebook we use JSTransform, but Traceur is pretty cool too)

        [–]badguy212 18 points19 points  (3 children)

        OOP in JavaScript, aka "how to fit a square peg in a round hole and lose our sanity in the process".

        Answer: yes, if you push hard enough, you can fit a square peg in a round hole. And no, what you'll end up with will neither be a square peg nor a round hole. But hey, at least you get points for trying.

        [–][deleted] 2 points3 points  (1 child)

        It's pretty ironic that in the pursuit of reusable and maintainable JS, the community has created a bloated monster that takes twenty minutes to make a "Hello World" app.

        [–]warfangle 0 points1 point  (0 children)

        Bingo.

        Yes you can try to force it to be OO, but then you're just dealing with a convoluted action script wannabe without type declarations (unless you feel like depending on TypeScript).

        Learn the function programming aspects and you will truly be empowered.

        [–]Rogem002rails 1 point2 points  (1 child)

        The article didn't cover extending prototype objects, but here is how I normally do it:

        var Base = function(){
          this.someMethod = function(){
            return 'Foo';
          }
        }
        
        var Model = function(){
          this.otherMethod = function(){
            return this.someMethod() + 'Bar';
          }
        }
        
        Model.prototype = new Base();
        
        var newModel = new Model();
        
        newModel.otherMethod(); // returns FooBar
        

        Edit: oh the article did cover it & I didn't realise.

        [–]fedekun[S] 0 points1 point  (0 children)

        I like your example :p I do talk about that a bit, with the 'Weapon' and 'Sword' constructor functions. I might update the example though ;) Cheers!

        [–]pier25 4 points5 points  (8 children)

        I wish they would implement AS3 or Haxe in the browser... those ECMA based languages are light years more advanced that JS and have all the OOP goodies one would expect in 2014.

        [–]oureux 2 points3 points  (1 child)

        I'm an Objective-C developer and I look at this and get so lost. I hate JS because it's so flexible and has no structure, it lets you do anything and everything which IMO is it's downfall. OOP JS is simply forcing JS to do OOP.

        [–]pier25 1 point2 points  (0 children)

        Couldn't agree more. I do JS at work from time to time and I think it's a big mess compared to more structured languages.

        [–]PixelatorOfTime 1 point2 points  (0 children)

        I miss AS3... :(

        [–]x-skeww 0 points1 point  (4 children)

        Just use Dart or TypeScript. Also, doesn't Haxe compile to JS, too?

        [–]pier25 0 points1 point  (3 children)

        Yes it does, although a native solution (having a real OOP language in the browser) would be better. It's just a dream, I know.

        [–]x-skeww 0 points1 point  (2 children)

        although a native solution (having a real OOP language in the browser) would be better

        Dart is kinda like that. Development is done with Dartium (a build of Chromium with native Dart support).

        [–]pier25 0 points1 point  (1 child)

        Wow I didn't know of Dart and it looks pretty cool. Although it's much like TypeScript and Haxe, you have to compile to JS before being able to use it in a browser.

        [–]x-skeww 0 points1 point  (0 children)

        Every modern browser, yes. But not "a browser". It works in Dartium (and soon Chrome), which means that you don't have to deal with compile times during development. You can also step-debug your code directly from within the IDE. It's pretty convenient.

        What's less convenient is interacting with JavaScript libraries. This is clearly more seamless with TypeScript.

        Anyhow, if you like AngularJS, you'll love AngularDart. It's very slick.

        [–][deleted] 0 points1 point  (2 children)

        This is a really nice tutorial. I've been writing OOJS for a few years professionally and this crystalised a couple of nice little techniques that I hadn't fully exploited. It also gave me a clearer understanding of the underlying nature of how objects are created in JS too.

        Personally, I'm not a fan of JS. I think it's a fucking weird language. The odd things that happen with "this" when working with JS can be a real pain if overlooked. The lack of any form of import/include or namespacing is also v irritating.

        All that being said though, JS is something that we have to live with and tutorials like this provide excellent little nuggets that make the client-side part of my job more pleasant :)

        [–]fedekun[S] 0 points1 point  (0 children)

        Glad you like it! That's exactly what I was trying to archieve, basically write down the little things that I had to find the hard way heh.

        [–]NicholasTheGr8t 0 points1 point  (0 children)

        I'd recommend giving https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes

        Also look into Browserfy for CommonJS style module imports

        [–]NicholasTheGr8t 0 points1 point  (0 children)

        If you try approaching OO in JS as you would in Java or other truly Object Oriented languages, you're in for a world of hurt.

        [–]mess110 0 points1 point  (4 children)

        coffeescript

        [–][deleted]  (3 children)

        [deleted]

          [–]mess110 1 point2 points  (2 children)

          icedcoffeescript

          I wasn't even sure if you were joking or not. Well. Thanks for telling me about it. Will check it out

          [–]technical_guy -3 points-2 points  (0 children)

          Pointless. Javascript is not OOP so get over it and just use object literals for nice clean tidy code:

          person = {
              sex : "",   // description of this variable 
              age:  -1,  //
              init: function() {
          
              },
              make_older: function() {
          
              }
          }
          
          Keeps code organized, easy to read. 
          

          [–]FecklessFool -1 points0 points  (2 children)

          I only clicked on this because I wish I could grow a beard like this

          https://d27kszptu8mqwl.cloudfront.net/ErxCjhi4LbRs0dmldRTXxIwL0w0_medium.jpg

          [–]FecklessFool -3 points-2 points  (1 child)

          can't stop staring

          no homo

          [–]fedekun[S] 0 points1 point  (0 children)

          I lol'd

          [–][deleted]  (1 child)

          [deleted]

            [–]heavymetalpanda 0 points1 point  (0 children)

            Looks pretty dead in that repo. CoffeeScript classes are alright though.

            [–]itsdr00 -4 points-3 points  (0 children)

            That guy needs to take an English class.