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 trialGinger Williams
6,409 PointsWhat is the difference between a constructor and a prototype or class?
It is not clear to me the difference between the two. Isn't a constructor like creating a new class? Is prototype not a class?
1 Answer
Ryan Duchene
Courses Plus Student 46,022 PointsPrototypes and classes are similar in what they do. In both cases, you have a template or blueprint that is used to create new objects of that type (for instance, a Dog
class or prototype).
A constructor is simply a function defined inside of a class or prototype that is automatically called whenever a new object of the class or prototype is created. It is used to set the initial state of variables inside of the object.
In PHP (which uses classes), a class and its constructor would be defined like this:
<?php
class Dog
{
public $name;
public function __construct($name)
{
// constructor sets up object
$this->name = $name;
}
}
$dog = new Dog("Shep");
echo $dog->name; // prints out "Shep"
In JavaScript (which uses prototypes), a constructor would look like this:
var Dog = function(name)
{
// constructor sets up object
this.name = name;
}
var dog = new Dog("Shep"); // the 'new' is really important here
console.log(dog.name); // prints out "Shep" to the console
I've talked about prototypes and classes as if they're the same things here. While they do accomplish similar goals, you should know that they are really quite different in their behavior. The JavaScript courses here do a much better job of explaining their differences than I will, however. :)