Ask HN: What's the point of a constructor function anyways?

6 points by ovatsug25 ↗ HN
While trying out a project in Javascript, I decided to finally learn a bit about the "prototype". I'm at the crossroads where I want to decide whether I want to use "pure" prototypal inheritance as with "Object.create" or whether I want to go with "new Class(params...)". As I investigate and weight between my choices, I realize that "When Object.create is used, it is like having only the prototype objects, and empty constructors." So what is the point of constructors anyways? Picking between Object.create and "new" is based on how important are constructors for getting things done. Can you help me brainstorm through this?

5 comments

[ 4.6 ms ] story [ 18.5 ms ] thread
Going back to Smalltalk, it seems like original OO was prototypal. I wonder what made them change this.

Here's the article I was just looking at:

http://onsmalltalk.com/objects-classes-and-constructors-smal...

Choice quotes

     But a constructor would really help pretty this up and encapsulate the knowledge about what fields are required for construction rather that forcing the client to individually initialize the object and hoping he does it correctly. So let's write a constructor for #Person, we'll put it on the "Person class", or the Person's class side as it'd normally be called.


      Some Smalltalk'ers prefer to write their constructors in a different style, one that enforces encapsulation a bit more, by not allowing public setters for all the instance variables, like so...

     Person class>>firstName: aFirstName lastName: aLastName
    ^(self new)
        initializeFirstName: aFirstName lastName: aLastName;
        yourself.

      Person>>initializeFirstName: aFirstName lastName: aLastName
    firstName := aFirstName.
    lastName := aLastName.
    relatives := Set new.

    Smalltalk is not so much a language, as an extensible notation for creating languages. To rip off a famed martial artist, empty your mind, be formless, shapeless, like Smalltalk. If you put Smalltalk into a financial application, it becomes a custom finance language. You put Smalltalk into a shipping application, and it becomes a custom shipping language. Be Smalltalk my friend.
If you want to trace to original OO, I believe you should go back to Simula.
The point of constructors in JavaScript was to mirror the "look" of Java. Brendan Eich has mentioned this. You don't technically need them and can use functions to return objects.