Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can someone explain to me what's the point of having syntax like:

`var foo = new Bar()`?

Why can't a constructor just be a regular method that happens to return a new instance? What's with this new nonsense?



I agree, this syntax makes little sense in dynamic languages where classes/types are first-class values that share the namespace with functions and ordinary values... Even in JavaScript, where it sort-of-kind-of makes sense, it introduces more problems than it solves.


Nitpick: you can make a constructor look like a regular method that happens to return a new instance, but you cannot make it one. How would that constructor make the instance that it returns?

I think the overhead of adding that 'new' is worth it. Without it: in var foo = Bar(), is Bar a type or a function? If you decide it should be colored like a type, your syntax colorer needs deeper information about the code, making it harder to write, slower, etc.


Not true, look at Objective-C for an example of how it's done. Broken up into two methods, the first of which is a static method which creates an uninitialized instance, and the second which is a plain method which initializes the instance and returns self (or rarely, nil):

    + alloc // reserves memory and creates an instance
    - init // initializes the instance
    - initWithSomething: // can have multiple inits


I go back and forth on whether I like this. On the one hand, the clean split makes it conceptually simple what's going on. On the other hand, you can have allocated, uninitialized code, which makes me uneasy.


You always chain together `alloc` / `init` calls, and so you're hardwired never to have a situation where you don't initialize something you've allocated. I think the compiler even knows to warn you about it, now.


>but you cannot make it one

Why not? It makes no difference whatsoever. Make it so that the only constructor in the system is Object.new(), and so everything else that inherits behaves just like a method.

>Without it: in var foo = Bar(), is Bar a type or a function?

That's easy. Make it so that only classes and consts can be capitalized.

Blammo!




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: