Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker

JavaScript constructors, prototypes, and the `new` keyword

Pivotal Labs
Friday, August 20, 2010

Are you baffled by the new operator in JavaScript? Wonder what the difference between a function and a constructor is? Or what the heck a prototype is used for?

I’m going to lay it out straight.

Now, there’s been a lot of talk for a long time about so-called “pseudo-classical” JavaScript. Mostly, the new guard of JavaScript folk don’t like to use the new keyword. It was written into the language to act more like Java, and its use is a little confusing. I’m not going to take sides here. I’m just going to explain how it works. It’s a tool; use it if it’s practical.

What is a constructor?

A constructor is any function which is used as a constructor. The language doesn’t make a distinction. A function can be written to be used as a constructor or to be called as a normal function, or to be used either way.

A constructor is used with the new keyword:

var Vehicle = function Vehicle() {
  // ...
}

var vehicle = new Vehicle();

What happens when a constructor is called?

When new Vehicle() is called, JavaScript does four things:

  1. It creates a new object.
  2. It sets the constructor property of the object to Vehicle.
  3. It sets up the object to delegate to Vehicle.prototype.
  4. It calls Vehicle() in the context of the new object.

The result of new Vehicle() is this new object.

1. It creates the new object.

This is nothing special, just a fresh, new object: {}.

2. It sets the constructor property of the object to Vehicle.

This means two things:

vehicle.constructor == Vehicle  // true
vehicle instanceof Vehicle      // true

This isn’t an ordinary property. It won’t show up if you enumerate the properties of the object. Also, you can try to set constructor, but you’ll just set a normal property on top of this special one. To wit:

vehicle;                          // {}

var FuzzyBear = function FuzzyBear() { };
vehicle.constructor = FuzzyBear;

vehicle;                          // { constructor: function FuzzyBear() }
vehicle.constructor == FuzzyBear; // true
vehicle instanceof FuzzyBear      // false
vehicle instanceof Vehicle        // true

The underlying, built in constructor property is something you can’t set manually. It can only be set for you, as part of construction with the new keyword.

3. It sets up the object to delegate to Vehicle.prototype.

Now it gets interesting.

A function is just a special kind of object, and like any object a function can have properties. Functions automatically get a property called prototype, which is just an empty object. This object gets some special treatment.

When an object is constructed, it inherits all of the properties of its constructor’s prototype. I know, it’s a brainful. Here.

Vehicle.prototype.wheelCount = 4;
var vehicle = new Vehicle;
vehicle.wheelCount;         // 4

The Vehicle instance picked up the wheelCount from Vehicle‘s prototype

Now this “inheritance” is more than simply copying properties to the new objects. The object is set up to delegate any properties which haven’t been explicitly set up to its constructor’s prototype. That means that we can change the prototype later, and still see the changes in the instance.

Vehicle.prototype.wheelCount = 6;
vehicle.wheelCount;         // 6

But if we like, we can always override it.

vehicle.wheelCount = 8;
vehicle.wheelCount          // 8
(new Vehicle()).wheelCount  // 6;

We can do the same thing with methods. After all, a method is just a function assigned to a property. Check it.

Vehicle.prototype.go = function go() { return "Vroom!" };
vehicle.go();                              // "Vroom!"

4. It calls Vehicle() in the context of the new object.

Finally, the constructor function itself is called. Inside the function, this is set to the object we’re constructing. (Why? Because that’s what Java does.) So,

var Vehicle = function Vehicle(color) {
  this.constructor;       // function Vehicle()
  this.color = color;
}

(new Vehicle("tan")).color;   // "tan"

Side note: Above, I said the use of the new keyword returned the constructed object. This is correct unless the constructor returns something explicitly. Then that object is returned, and the constructed object is just dropped. But really. JavaScript slaves over a hot CPU to create this object for you and then you just throw it away? Rude. And confusing to people who use your constructor. So unless you have a really good reason, don’t return anything from constructor functions.

Putting it all together

Given this tool, here’s one way (the intended way, but not the only way) to implement something like classes in JavaScript.

// Class definition / constructor
var Vehicle = function Vehicle(color) {
  // Initialization
  this.color = color;
}

// Instance methods
Vehicle.prototype = {
  go: function go() {
    return "Vroom!";
  }
}

“Subclassing”

This “pseudoclassical” style doesn’t have an exact way to make subclasses, but it comes close. We can set the prototype of our “subclass” to an instance of the “superclass”.

var Car = function Car() {};
Car.prototype = new Vehicle("tan");
Car.prototype.honk = function honk() { return "BEEP!" };
var car = new Car();
car.honk();             // "BEEP!"
car.go();               // "Vroom!"
car.color;              // "tan"
car instanceof Car;     // true
car instanceof Vehicle; // true

Now, there’s a problem here. The Vehicle constructor only gets called once, to set up Car‘s prototype. We need to give it a color there. We can’t make different cars have different colors, which is not ideal. Some JavaScript frameworks have gotten around this by defining their own implementations of classes.

And for my last trick…

Sometimes you don’t want a notion of classes. Sometimes you just want one object to inherit the properties of another (but be able to override them). This is how most prototype-based languages work, but not JavaScript. At least, not without a little massaging.

This function lets us accomplish it. It’s been tossed around for a long time and is sometimes called “create” and sometimes “clone” and sometimes other things.

function create(parent) {
  var F = function() {};
  F.prototype = parent;
  return new F();
}

var masterObject = {a: "masterObject value"}

var object1 = create(masterObject);
var object2 = create(masterObject);
var object3 = create(masterObject);
var object3.a = "overridden value";

object1.a; // "masterObject value"
object2.a; // "masterObject value"
object3.a; // "overridden value"

masterObject.a = "new masterObject value"

object1.a; // "new masterObject value"
object2.a; // "new masterObject value"
object3.a; // "overridden value"

You said a mouthful.

The JavaScript prototype chain is a little different than how most languages work, so it can be tricky understand. It doesn’t make it any easier when JavaScript gets syntax that makes it looks more like other languages, like inheriting Java’s new operator. But if you know what you’re doing, you can do some crazy-cool things with it.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter

8 Comments

  1. Clay Shentrup says:

    Good stuff. These are JavaScript fundamentals, but a lot of people write a significant amount of JavaScript without ever being aware of any of this. Not to say they can’t skin the cat some other way, but you can write some clean sexy code using this knowledge.

    I’m curious what you think about this general method of JS inheritance that I created as a Frankenstein of the Crockford and MDC recommendations.

    http://brokenliving.blogspot.com/2009/09/simple-javascript-inheritance.html

    Maybe there’s an even better way, and if so I’d like to know it.

    August 21, 2010 at 12:57 pm

  2. Peter Jaros says:

    Ooh, that looks nice!

    August 30, 2010 at 12:05 pm

  3. Pingback: Adding callbacks to Twitter Bootstrap’s Javascript plugins | Teknotica's blog

  4. Olegs Klujs says:

    Thanks, it helpt me a lot.

    March 21, 2013 at 5:40 am

  5. Aamir Afridi says:

    Thanks for explain everything in such a clear way.

    March 22, 2013 at 9:43 am

  6. Javed Akhter says:

    Ooh, that’s very sharp and clean way! It helped me a lot.

    April 3, 2013 at 2:39 am

  7. Kyle Simpson says:

    > It sets the constructor property of the object to Vehicle.
    > This isn’t an ordinary property. It won’t show up if you enumerate the properties of the object. Also, you can try to set constructor, but you’ll just set a normal property on top of this special one.
    > The underlying, built in constructor property is something you can’t set manually. It can only be set for you, as part of construction with the new keyword.

    This is incorrect information. The spirit of what you’re saying is nice, but it represents a fundamental mis-understanding of how prototypes and delegation work.

    In your example, `Vehicle.prototype` is the object that has a `.constructor` property on it, pointing to `Vehicle()`. Try it: `Vehicle.prototype.constructor === Vehicle`. Note: this `.constructor` property was ONLY automatically added to the default `.prototype` object of the Vehicle function. If you make your own objects and use them as a constructor’s `.prototype`, they won’t be default have a `.constructor` property added to them, though you can add it yourself if you want (and many do, when using subclasses).

    Want proof where `.constructor` actually lives? `Vehicle.prototype.hasOwnProperty(“constructor”); // true` and `vehicle.hasOwnProperty(“constructor”); // false`.

    When you `vehicle.constructor === Vehicle`, you’ve tricked yourself into believing that property exists there. What’s actually happened is that since `.constructor` didn’t exist on `vehicle` object, it **delegated** that property access up to his [[Prototype]] linked object, which happens to be `Vehicle.prototype`. Since we’ve established that `Vehicle.prototype` **does have** a `.constructor`, that object is able to handle the property access, and it is indeed pointed at `Vehicle()`.

    April 23, 2013 at 11:34 am

  8. Perminder says:

    Loved the explanation….cleared a lot of ambiguities..thanks

    May 8, 2013 at 7:56 am

Add New Comment Cancel reply

Your email address will not be published.

Pivotal Labs

Pivotal Labs

Recent Posts

  • Does the set of all sets contain itself?
  • Standup 3/8/2012
  • Standup 3/7/2012
Subscribe to Pivotal's Feed

Author Topics

riddles (1)
agile (167)
capistrano (2)
rails (26)
movember (1)
git (10)
railsdoc (1)
object-design (1)
bdd (3)
cucumber (3)
linkedin (1)
oauth (1)
ruby (17)
tdd (2)
lvh.me (1)
rails 3.1.1 (1)
selenium (6)
homebrew (1)
mysql (5)
rvm (1)
sproutcore (1)
paperclip (2)
pry (1)
amazon (1)
heroku (1)
rails3 (2)
jasmine (3)
design (3)
process (12)
productivity (8)
learning (1)
olin (1)
migrations (2)
mongodb (2)
devise (2)
javascript (13)
rubymine (4)
ipad (1)
whurl (1)
head.js (1)
pairing (2)
tools (4)
pair programming (1)
rspec (10)
rspec2 (1)
ruby19 (1)
incubation (3)
startup (5)
api (1)
presenter (1)
vanna (1)
pivotal tracker (5)
capybara (1)
fakeweb (1)
webmock (1)
intern (1)
ruby on rails (25)
meetup (1)
textmate (1)
testing (20)
solr (4)
nyc-standup (11)
community (1)
opensource (3)
activerecord (4)
chrome (1)
mp4 (1)
activeresource (1)
flash (3)
neo4j (1)
nginx (1)
rsoc (1)
meta programming (1)
agile standup (7)
government (3)
webos (4)
xss (1)
jquery (1)
bundler (2)
ci (3)
gems (5)
postgresql (1)
geminstaller (1)
gemcutter (1)
cloud (2)
rack (2)
refraction (1)
gem (5)
refactoring (1)
validations (1)
webrat (1)
engine-yard (1)
firefox (2)
jsunit (1)
mongrel (2)
thin (1)
unicorn (1)
facebook (1)
rubygems (5)
jruby (1)
actioncontroller (1)
rails 2.3 (1)
palmpre (1)
autotest (1)
mac (2)
hosting (1)
goruco (11)
database (3)
railsconf (11)
gogaruco (4)
deployment (4)
github (1)
ie (1)
ajax (1)
intellij (1)
json (1)
asset packaging (1)
polonium (1)
character encoding (1)
utf-8 (1)
test (3)
civics (1)
hpricot (1)
rake (3)
sms (1)
unicode (1)
iphone (1)
java (1)
safari (1)
memory leaks (1)
rr (3)
editor (1)
css (1)
nyc (3)
performance (5)
fun (5)
enterprise rails (1)
health (1)
new and cool (1)
general (2)
treetop (1)
errors (1)
stack (1)
trace (1)
cache (1)
cookies (1)
freesoftware (1)
conferences (1)
development (1)
driven (1)
proxy (1)
caching (1)
peertopatent (1)
languages (1)
rest (2)
rubyforge (1)
sake (1)
file (1)
upload (1)
constants (1)
osx (1)
terminal (1)
pairprogramming (2)
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >