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 Introducing ES2015 Classes Sub-Classes

Greg Schudel
Greg Schudel
4,090 Points

what is a constructor function

what exactly is a constructor function?

I read this online: "The this keyword in an object constructor does not have a value." from https://www.w3schools.com/js/js_object_definition.asp Know of any short courses on constructor functions?

nico dev
nico dev
20,364 Points

This video and the course itself also talk about it.

And it's also always a good idea to check the MDN explanations and examples, too.

3 Answers

Tom Geraghty
Tom Geraghty
24,174 Points

In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Don't get hung up on subroutine, think of that as a function.

Creating a Class is creating an idea. Creating an instance is creating an actual thing. So you can imagine the idea of a Person having properties such as name, age, height, hair color, etc. All of those properties are properties of the class that can have different values. When you create an instance of a class you create an actual object that has each of the properties assigned an actual value (you can use default values of course).

The class creates the mockup or idea of what you want in your program. The constructor function is the special function within a class definition that allows actual values to be set for the properties of that class.

You create an instance of a class by using the new keyword. var Jimbo = new Person(name: Jimbo); Now you can use Jimbo in your program!

See: https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

There is additional information regarding constructor functions on the page you have linked to under the heading 'Using Object Constructors'. Did you try reading that, yet?

Greg Schudel
Greg Schudel
4,090 Points

Thanks nico, that helps alot. Ted, sometimes seeing a video helps more since sometimes I get lost in the lingo. thanks again to you both.