Search code examples
javascriptprototype-programming

Is there a good use case for the constructor property in Javascript?


First off, this question is not "what does the constructor property do?" - There's plenty of good documentation on exactly what it is and how it works: It's a reference to the function that created the object (which may be inherited from its prototype).

I'm more interested in knowing common use-cases for this property. It seems all good in theory, but when would you actually need a reference to the function that constructed your object? A few ideas would be:

  • Perhaps I want to clone it. I could call the constructor again and get another instance of my object. This of course wouldn't work well since you'd potentially be creating an instance of your object's prototype, not the object itself; plus a much preferred method would be to create a new object and set that object's prototype instead.
  • Perhaps you can use it to figure out what the "type" of the object is. This seems rather odd, since you can use instanceof or Object.prototype.toString() instead.
  • Can you change or re-assign the constructor? Would there ever be a good reason to do this?

Hopefully some people can chime in with some good Javascript paterns that make use of the constructor reference, or provide an official explanation for why the property exists.


Solution

  • One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.

    function foo(arg) {
      if ( /* if arg is an array */ ) {
        // deal with array
      } else if ( /* if arg is an object */ ) {
        // deal with object
      }
    }
    

    If the above function is passed an array or object, then typeof will return object in both cases. The constructor property can be used:

      if ( arg.constructor == Array )
    

    But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).

    So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.

    But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.