Hacker News new | past | comments | ask | show | jobs | submit login

You aren't "required".

    function C(x) {
      var self = {};
      self.x = x;
      return self;
    }

    C(1).x === (new C(1)).x
The thing about javascript is that the concept of constructors and prototypes is so simple and flexible that there's many different ways you can go about structuring your code for inheritance. That's the reason there's so many frameworks that do inheritance differently.

EDIT: On re-reading your post, I wonder what you mean by saying that python's constructors are more similar to functions, compared to javascript's? In javascript, there is no difference at all between constructors and functions. They are simply functions that construct an object and that's it. The capital letter is simply a convention. The use of `this` and `new` is a facility for an implicit variable that javascript provides, but is no less powerful without it.

EDIT 2: Reworded EDIT 1 because I might be confusing python's classes with constructors. I wonder if the parent referred to `__init__`.




I haven't done any JS in about 7 years, but back in the day I used to program like this:

    var make_person = function(name) {
      var say = function(what) {
        console.log(name + " says: " + what);
      };
      return {
        name: name,
        greet: function(who) {
          say("Hi " + who.name + ". It's " + name + ".");
        }
      }
    };

    make_person("John").greet(make_person("Jane"));
I wonder if this was ever idiomatic.


This method is less efficient than using prototypes because the created instance will lug around an object with its own function, instead of sharing one. Sometimes I use "factories" for cases where my instance only needs one method or if the number of instances is going to be relatively small.


My understanding is that the parent's comment was in the context of instantiating a class, rather than in the context of underlying definitions. Because Python constructors are nothing like regular functions; there is a lot more "magic" happening underneath when instantiating a Python class than in the case of Javascript.




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

Search: