Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Constructors Review

jayshi
jayshi
5,950 Points

Difference between constructor function and instance

I was doing multiple choices questions on constructor function chapter. but i cant tell the if the function is an instance or a constructor function.

2 Answers

Oliver Duncan
Oliver Duncan
16,642 Points

A constructor function is the function we use to create a custom object in JavaScript, while an instance is a just that - an instance of our custom Object. Take a custom object, Animal:

// constructor function
func Animal(name, soundItMakes) {
  this.name = name
  this.soundItMakes = soundItMakes
}
// an instance
var cow = new Animal("cow", "moo") // returns Animal { name: "cow", soundItMakes: "moo" }
// another instance
var sheep = new Animal("sheep", "baa") // returns Animal { name: "sheep", soundItMakes: "baa" }

So anytime you see the keyword "new", that's a clue that you're looking at an instance. If you're seeing a function, chances are that it's a constructor function. Hope this helps.

Presley Cobb
Presley Cobb
9,214 Points

The first thing you should know is that a constructor is dependent on having an instance. So you first need to know what an instance is. An instance is just a representation of an object. So like how a cow or a dog is a representation of an animal.

So what the constructor does is run code at the moment you create the instance. So if you want to create a dog and at the time of creation you want to give it a name like Scruffy that would be the constructor code. By constructor code I mean the code to set name = scruffy.