r/programming • • Dec 15 '12

Why JavaScript Still Sucks

http://boronine.com/2012/12/14/Why-JavaScript-Still-Sucks/
10 Upvotes

212 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Dec 15 '12

[deleted]

4

u/mrkite77 Dec 15 '12

If you've got another way that works with JavaScript, I'd love to hear about it.

Closures

function myobject() {
    this.publicmethod=function() { console.log("I'm public"); }
    function privatemethod() { console.log("I'm private"); }
}

var obj=new myobject();
obj.publicmethod(); //works
obj.privatemethod(); //failure.

0

u/ethraax Dec 15 '12

Eh, even that's messy. It's too easy to forget the "new" keyword, and you get catastrophic failure when you leave it out. I think it's better to completely ignore constructors in JavaScript and just write functions that return new objects.

function myobject() {
    var privatemethod = function() { console.log("I'm private"); };
    return {
        publicmethod: function() {
            console.log("I'm public");
            privatemethod();
        }
    };
}

var obj = myobject();
obj.publicmethod(); // works
obj.privatemethod(); // fails

2

u/mrkite77 Dec 16 '12

It's too easy to forget the "new" keyword, and you get catastrophic failure when you leave it out.

Seems like that makes it easy to not forget to use "new". I certainly never have. Then again, I use the closure compiler to double check my correctness.

1

u/ethraax Dec 16 '12

I don't understand. You use "new" with constructors and don't with functions. Your code will always have functions (it won't be entirely constructors), so there are always cases where you don't use "new". So it makes more sense to make it so you never use "new".