Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion

JavaScript Objects

  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter

JavaScript Prototype

  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment

JavaScript Classes

  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Methods and this Keyword

  • JavaScript Object.getPrototypeOf()

JavaScript Constructor Function

In JavaScript, a constructor function is used to create objects . For example,

In the above example, function Person() is an object constructor function.

To create an object from a constructor function, we use the new keyword.

Note : It is considered a good practice to capitalize the first letter of your constructor function.

Create Multiple Objects with Constructor Function

In JavaScript, you can create multiple objects from a constructor function. For example,

In the above program, two objects are created using the same constructor function.

  • JavaScript this Keyword

In JavaScript, when this keyword is used in a constructor function, this refers to the object when the object is created. For example,

Hence, when an object accesses the properties, it can directly access the property as person1.name .

JavaScript Constructor Function Parameters

You can also create a constructor function with parameters. For example,

In the above example, we have passed arguments to the constructor function during the creation of the object.

This allows each object to have different properties. As shown above,

console.log(person1.name); gives John

console.log(person2.name); gives Sam

Create Objects: Constructor Function Vs Object Literal

  • Object Literal is generally used to create a single object. The constructor function is useful if you want to create multiple objects. For example,
  • Each object created from the constructor function is unique. You can have the same properties as the constructor function or add a new property to one particular object. For example,

Now this age property is unique to person1 object and is not available to person2 object.

However, if an object is created with an object literal, and if a variable is defined with that object value, any changes in variable value will change the original object. For example,

When an object is created with an object literal, any object variable derived from that object will act as a clone of the original object. Hence, any change you make in one object will also reflect in the other object.

Adding Properties And Methods in an Object

You can add properties or methods in an object like this:

In the above example, a new property gender and a new method greet() is added to the person1 object.

However, this new property and method is only added to person1 . You cannot access gender or greet() from person2 . Hence the program gives error when we try to access person2.greet();

  • JavaScript Object Prototype

You can also add properties and methods to a constructor function using a prototype . For example,

To learn more about prototypes, visit JavaScript Prototype .

  • JavaScript Built-in Constructors

JavaScript also has built-in constructors. Some of them are:

In JavaScript, strings can be created as objects by:

In JavaScript, numbers can be created as objects by:

In JavaScript, booleans can be created as objects by:

Note : It is recommended to use primitive data types and create them in a normal way, such as const name = 'John'; , const number = 57; and const count = true;

You should not declare strings , numbers , and boolean values as objects because they slow down the program.

In JavaScript, the keyword class was introduced in ES6 (ES2015) that also allows us to create objects. Classes are similar to constructor functions in JavaScript. To learn more, visit JavaScript Classes .

Table of Contents

  • Introduction
  • Multiple Objects with Constructor
  • JavaScript Constructor Parameters
  • Constructor Function Vs Object Literal
  • Adding Properties And Methods

Sorry about that.

Related Tutorials

JavaScript Tutorial

DEV Community

DEV Community

Lawrence Eagles

Posted on May 9, 2020 • Updated on Jun 12, 2020

An Easy Guide To Understanding Constructors In JavaScript

Table of contents.

  • An Introduction To Constructors
  • Functions, Constructors And The new Operator
  • Constructors And Prototypal Inheritance
  • JavaScript's Built-In Constructors
  • Closing Thoughts

1. An Introduction To Constructors

In the previous article in this series, we looked at prototypal inheritance in JavaScript and talked about important object-oriented (OOP) JavaScript concepts like the prototype, the prototype chain, inheritance, and more. We also looked at how to set an object's prototype using its __proto__ property ( we noted that this is not the recommended way. ) and dealt with the this variable in detail. You can read through this article below:

lawrence_eagles

Understanding Prototypal Inheritance In JavaScript

Lawrence eagles ・ apr 23 '20 ・ 13 min read.

In this article, we would pick up where we left off by looking at the recommended ways to set an object's prototype in JavaScript. While there are several ways to do this, our focus here is on function constructors.

✨ We will deal with the other recommended methods in the upcoming articles in this series. Talking in detail about all of them; in a single article would make it very long and grueling to read!

Constructors

Constructors in JavaScript are special functions that are used to construct objects. This topic may appear difficult and intimidating but it is actually very simple.

💡 The key to understanding constructors is to know that they are actually normal JavaScript functions. What makes them special is that they are always invoked along with a very powerful operator in JavaScript called the new operator.

Kindly run the code below and consider its result.

Our small contrieved example above creates a new object and stores a reference to it in the Lawrence variable. This object has all the properties specified in the Person constructor. The Person function itself is a normal JavaScript function; what gives it the power of a constructor ( the power to construct objects ) is this line of code:

✨ The new operator modifies the behaviour of the function it operates on. Using this along with some JavaScript design patterns, we are able to create powerful constructors. We will elaborate on this in the next section.

2. Functions, Constructors And The new Operator

In section 1 we learned that when the Person constructor, (or any other constructor) is invoked without the new operator it is invoked as a regular JavaScript function. In this section, we will elaborate on this with code examples. Kindly consider the code below.

Above is the declaration of the Person function. We can notice two things from it viz:

  • It sets some properties e.g firstname, lastname, occupation, and gender to the object the this variable binds (or is pointing) to. In this case the global object.
💡 As mentioned in the previous article in this series, one rule of the this variable is that when it is used inside a function it points to the global object but when it is used inside a method (a function in an object) it would point to that object

If this is not very clear to you, feel free to visit my previous article on OOP JavaScript. I have already provided a link to it in section 1. However, here is a quick recap. Kindly run the code below and consider its result

The above example shows that the this variable inside a function is pointing to the global object.

  • Another thing that should be pretty obvious about the Person function is that it does not have a return statement hence when invoked it would return undefined.
💡 The JavaScript engine would return undefined from any function that does not return a value. This behaviour is leveraged in creating constructors as we are able to modify what that function returns using the new operator. Hence it is a common pattern in JavaScript, that constructors do not have a return statement

The New Operator

This is a very powerful JavaScript operator that has the ability to modify certain behaviours of a function. The new operator can be very confusing and somewhat intimidating at first.

✨ The key to understanding it is to always see it as another regular JavaScript operator. Hence, a good understanding of operators in JavaScript is necessary to grasp the power of this operator .

Operators are special JavaScript functions that are syntactically different from regular functions. They are not like a regular JavaScript functions objects hence passing them to console.dir() would throw an error. You can see some code examples below. Kindly run the codes below and consider the results:

💡 The console.dir() displays an interactive list of the properties of the specified JavaScript object

codes result from runkit

You can see all the properties of the tellDevName function and the Date constructor when you run the code but if you uncomment the lines where I passed an operator as a parameter, and try to run the code, runkit would throw an error, this tells us that they are not regular function objects.

Operators much like regular functions take parameters (which are called operands) but unlike regular functions, they give us a convenient syntax which can be in the form of any of the three notations below:

  • Infix Notation: In this notation, operators are placed between their operands. Kindly consider the code below:

In our examples above each operator sits between two parameters (operands) and returns a value. Learn more about the infix notation here

  • Postfix Notation: In this Notation, the operators follow their operands. Kindly consider the codes below:

Above is a small example that finds the even number from a list of numbers. But what concerns us from this example is the increment operator. There is also the decrement operator. Learn more about the postfix notation Kindly consider the code below:

  • Prefix Notation: In this notation, the operator precedes its operands. Learn more about the prefix notation Kindly consider the codes below:

From our examples above we can see that the new operator uses the prefix notation it takes a function (constructor) invocation and returns a newly constructed object.

🎉 I do hope that our succinct discourse on operators, would make you understand the new operator better and hence further your understanding of function constructors

With our understanding of operators, we can now clearly see that the new operator actually takes a function (constructor) invocation as its parameter(operand) it then performs some operations on it and returns a value. Below are the operations of the new operator on a function constructor.

  • Creates an empty object and binds (points) the this variable to the newly created object.
  • Returns the object the this variable binds to (the newly created object) if the function doesn't return its own object (this is why constructors should not have a return statement) . Kindly run the codes below and consider the results:

From the code example above I have deliberately given 2 of the 3 functions the same name but since JavaScript is case sensitive they are two different functions. Notice that the first letter of the constructor's name is capitalized while the regular function name is all lowercase.

💡 We use this pattern in JavaScript to differentiate constructors from regular functions. The first letter of a constructor's name is always capitalized. This would also serve as a reminder for you to use the new operator with every constructor. In our code example above, Person is the constructor and person is the regular function.

We can see from the result of the code above that the regular function returns undefined as expected but the constructor returns a new object created by the new operator which also binds the this variable in that constructor to this object.

💥 Also notice the BadPerson constructor that returns its own object fails to return the object created from the new operator. This is a pitiful we must avoid. Again, as a rule, a constructor should not have a return statement❗

Alt JavaScript constructor's result

JavaScript Design Patterns For Creating Constructors

With our knowledge of constructors and the new operator, we can easily add properties to the newly constructed object . Here is a common JavaScript pattern for this. Kindly consider the code below

The only limitation here is that any object created by this constructor is always going to have these properties. In other to make the object properties dynamic, we can pass them as parameters to the constructor (since constructors are regular functions in the first place). Kindly run the codes below and consider its result:

From the results of running the code above, we can see that the arguments passed to each constructor, when invoked with the new operator are used to set up the properties of the newly constructed objects. You can read more about the new operator at MDN .

  • Lastly the new operator links (sets) the prototype of the newly created object to another object. In our introduction, we said we were going to talk about the recommended ways to set an object's prototype and our focus was on function constructors. This point brings our long discourse back to the subject matter. Let's talk more about it in the next section.

3. Constructors And Prototypal Inheritance

In JavaScript, every function has a property called the prototype . This sits as an empty object in the function and remains dormant throughout the life of that function. It would only become active and quite useful if that function is used as a constructor.

💡 The prototype property of a function (which is an object in JavaScript) is not the prototype of that function object but it acts as the prototype of any object constructed with that function when it is used as a constructor. The naming is a little confusing but we love our JavaScript 😉

Kindly run the code below and consider its result:

From the results of the code above we can see that all the objects constructed with the Person constructor have access to the getPersonbio method which sits in the prototype property of the Person constructor. As we have noted above this property becomes the prototype of each object.

✨ The details of how the search is made down the prototype chain in other for all the constructed object to access the getPersonBio method has already been discussed in the previous article. I would kindly suggest you take a look at it if this section is not very clear to you.

4. JavaScript's Built-In Constructors

JavaScript comes with some built-in constructors. If you are a JavaScript developer, there is a high probability that you have used some of them. Kindly run the code below and consider its result:

From running the codes above we can see that each returns an object because every constructor in JavaScript returns an object. You can learn more about each of these built-in constructors from the links below: Number Constructor String Constructor Date Constructor

✨ These are just a selected few you can get a more robots list here

5. Closing Thoughts

I do hope you followed through to this point. If you did you are really appreciated. It has been a long discussion, and I hope you got a thing or two. If so, I would now be looking forward to hearing your opinions, comments, questions, or requests (in case anything is not clear) in the comments section below.

Top comments (2)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

jisokoo profile image

  • Joined Sep 30, 2022

Hello, First thanks a lot for these useful article, really help me understand the concepts. Just a little thing I can't figure out: in the example of section 3. why does the results log the following: "Hello my name is Eagles Lawrence I am a Software Developer" "Developer's bio:" undefined

I understand the first line but why is "Developer's bio:" after sentence "Hello my name is ..." ? And why does it returns undefined after? Hope you can help me see this clearer Thanks

b2gogoi profile image

  • Joined Jan 23, 2023

Its because the function ( getPersonBio ) just has a console.log which gets executed first and not returning anything so undefined later

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

aortega profile image

Introvertish to Extrovertish

Alverto Ortega - Apr 5

rksalo88 profile image

Learning AWS Day by Day — Day 24 — S3 Introduction — Part 2

Saloni Singh - Apr 2

opensourceadvocate profile image

Shredding The Illusion Li-Cycle And The Dark Side Of Green Companies

Enri Marini - Apr 2

adityaoberai profile image

Social media authentication: convenience vs privacy

Aditya Oberai - Apr 2

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Home » JavaScript Tutorial » JavaScript Constructor/Prototype Pattern

JavaScript Constructor/Prototype Pattern

Summary : in this tutorial, you’ll learn how to use the JavaScript constructor/Prototype pattern to define a custom type in ES5.

Introduction to the JavaScript Constructor / Prototype pattern

The combination of the constructor and prototype patterns is the most common way to define custom types in ES5. In this pattern:

  • The constructor pattern defines the object properties.
  • The prototype pattern defines the object methods.

By using this pattern, all objects of the custom type share the methods defined in the prototype. Also, each object has its own properties.

This constructor/prototype pattern takes the best parts of both constructor and prototype patterns.

JavaScript Constructor / Prototype example

Suppose that you want to define a custom type called Person that has:

  • Two properties firstName and lastName .
  • One method getFullName() .

First, use the constructor function to initialize the properties:

Behind the scenes, the JavaScript engine defines a Person function denoted by the circle and an anonymous object denoted by the square.

The Person function has the prototype property that references an anonymous object. The anonymous object has a constructor property that references the Person function:

Second, define the getFullName() method in the prototype object of the Person function:

JavaScript defines the getFullName() method on the Person.prototype object like this:

Third, create multiple instances of the Person type:

Javascript creates two objects p1 and p2 . These objects link to the Person.prototype object via the [[Prototype]] linkage:

Each object has its own properties firstName and lastName . However, they share the same getFullName() method.

When you call the getFullName() method on the p1 or p2 object, the JavaScript engine searches for the method on these objects. Because the JavaScript engine doesn’t find the method there, it follows the prototype linkage and searches for the method in the Person.prototype object.

Because the Person.prototype object has the getFullName() method, JavaScript stops searching and executes the method.

Put it all together:

Classes in ES6

ES6 introduces the class keyword that makes the constructor/prototype pattern easier to use. For example, the following uses the class keyword to define the same Person type:

In this syntax, the class moves the property initialization to the constructor method. It also packs the getFullName() method in the same place as the constructor function.

The class syntax looks cleaner and less verbose. However, it’s syntactic sugar over the constructor/prototype pattern with some enhancements.

For more information on the classes, check out the JavaScript class tutorial .

  • Use JavaScript constructor/prototype to define a custom type in ES5.
  • Initialize the object properties in the constructor function and define methods and properties that can be shared by all instances in the prototype object.

Alex Devero Blog

Learn about development, and programming, especially in JavaScript, TypeScript and React, and design.

Getting Started With JavaScript Constructor Functions

Getting Started With JavaScript Constructor Functions feature image

Table of Contents

JavaScript offers multiple ways to create objects. These ways include object literals, Object() , classes and constructor functions. This tutorial will show you the third option. You will learn about what constructor function are, how they work, and how to use them to create objects.

Objects, blueprints, constructors

In JavaScript, there are multiple ways you can use to create objects. The easiest tools you can use are object literals , new Object() or Object.create() . However, what if you want something more different? What if you create an object you can than use as a blueprint, or a recipe, for creating other, similar, objects?

Imagine you want to create a couple of objects all having the same properties, maybe also methods. You can definitely do this object literal. However, it will require copying a lot of code. Or, it will require unnecessary cloning of objects, which can be sometimes quite unpredictable.

Another option is to create something called “constructor”. This constructor can have a number of various properties and methods and you can use it to create new objects. Each object you create with this constructor will also have all properties and methods defined in the constructor. This can save you a lot of time and code.

One way to create this constructor is by using JavaScript classes introduced in ES6. Another option is to use something called “constructor functions”. Let’s take a look at what this constructor function are, how they work, and how to use them to create objects.

The basics of constructor functions

The syntax of constructor functions is simple and straightforward. This is especially true if you know JavaScript functions. Syntax of these two is almost identical. Every constructor function starts with the function keyword. What follows is the name of the name of the constructor function.

The name of constructor function should start with a capital letter. This is not required, but it is a popular convention and good practice. However, if you use lowercase letter it will work. Next are parentheses with parameters. Even if you don’t want to specify any parameters, you still have to include the parentheses anyway.

The last is the function body that follows after the parentheses with parameters. This body is the place where you specify properties and methods for the constructor. When you use this constructor to create new objects they will all have these properties and methods.

Creating objects with constructor function

Creating constructor functions is one thing. Using them to create new objects is another. Luckily, there is only one way to do this. When you want to create new object using constructor function you use the new keyword. This keyword is followed by the constructor name and set of parentheses.

If your constructor accepts any parameters, pass any necessary arguments inside the parentheses. Otherwise, leave them empty. You will usually do this along with assigning new object to a variable. Remember that you can use constructor functions to create as many objects as you want.

Defining properties, methods

Defining properties, and methods, in constructor functions is simple. That said, there is one thing you have to remember. When you want to define property or method you have to use the this keyword. Don’t use let , const or var to do this. You are not trying to define a variable, but a property.

So, on the left side, start with the this keyword and then specify the name of the property. Add dot ( . ) between these two. On the right side, define the value for the property and you are done. If you want to define a method the process is almost the same. You also have to use the this keyword, followed by the name of the method.

The only difference is on the right side. Here, you have to use the function keyword. This will tell JavaScript that you want to define a function. You can also use an arrow function instead of a regular function. When you define a constructor method, you can access any property that already exists inside the constructor.

In order to access the property, to reference it correctly, you have to use the this keyword. The this in this case is a reference for the constructor function itself. So, this is basically like constructorFunctionItself .

Defining properties and methods outside the constructor

Defining properties and methods only inside the constructor function when you define it is one option. Another option is defining them outside it, after the constructor is created. In this case, you will use a property called prototype . This is a special property every function in JavaScript has.

This prototype property is an object that contains all properties and methods defined on a constructor function. It also contains constructor property. This property points to the constructor you are working with in the moment. Using this property allows you to add properties and methods to constructor, change or remove them.

Note about prototype : As you can see on the example above, there is one thing to remember. When you add property or method to a constructor via prototype, you also add it to all objects already created with that constructor.

Defining properties and methods for constructor objects

Sometimes you may want to add a property or method, but only to one object, not all. In this case, prototype is not an option since that would add the property or method everywhere. What you can do instead is to add the property or method directly to specific object. For example, using the dot notation.

After this, only the object at hand will have that new property or method. Other objects created with the same constructor will not. This is the way you would use to add a property or method to a regular object. Every object created with a constructor is an object. So, this works here as well.

Constructor functions and parameters

The option to create blueprint for objects is nice. So far, you’ve seen examples of constructors where all data were static and couldn’t be changed. This doesn’t mean that this is the only way. In the beginning, when we talked about the syntax, I briefly mentioned parameters.

This is how you can make constructor functions more dynamic. Just like you can define parameters for regular functions you can define them also for constructors. In case of constructors, you specify arguments when you create objects with the new keyword. You pass these arguments in the parentheses that follow the construct name.

When you define some parameters for a constructor, you can then use it anywhere inside the constructor. Take the Person constructor you’ve been working throughout this tutorial. It usually contained two properties: name and age . Having these two properties the same for all objects doesn’t make sense.

Instead of having both properties defined with static values, you can add two parameters for the constructor. One parameter for each property. Then, inside the constructor, you can use these parameters to assign those properties with provided values. This will allow you to create objects with different values for name and age properties.

A word about constructor functions and this

The this keyword is very important when you work with constructor functions. You use it when you want to define new properties and methods. You also use this keyword when you want to access some property and call some method. However, it doesn’t matter how often you have to use this keyword.

Understanding what this is, what it refers to, at the time can still be sometimes a difficult question to answer. Here is the simple answer. The value of this can be one of two things. First, when you are in a function constructor, the value will be the constructor.

Second, when you create new object with the constructor the value of this will become the new object. This will apply to every instance, every new object you create. The value of this will always be that specific object.

Conclusion: Getting started with JavaScript constructor functions

Constructor functions can be a useful when you want to create multiple objects with the same shape, but less code. They can also make your code easier to change and maintain. I hope that this tutorial helped you understand what constructor function are, how they work, and how to use them to create objects.

Do you have any questions, recommendations, thoughts, advice or tip you would like to share with other readers of this blog, and me? Please share it in a comment. You can also send me a mail . I would love to hear from you.

If you liked this article, please subscribe so you don't miss any future post.

Also, you can find me on GitHub , Twitter and Dribbble .

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

Buy Me A Coffee

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Kevin Chisholm – Blog

Web Development Articles and Tutorials

The JavaScript “this” Keyword Deep Dive: Constructor Functions

Learn how the javascript “this” keyword differs when instantiating a constructor (as opposed to executing the function)..

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog” .

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/2RFa3/

Example # 2.

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/2RFa3/1/

Example # 3.

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/2RFa3/2/

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

[…] When you instantiate a constructor function, inside of the instance object, “this” refers to the… […]

[…] A: In a non-constructor function, “this” refers to the global context or if the function is a method, it refers to the object to which the method belongs. In the instance object that is returned by a constructor function, “this” refers to the instance object itself. […]

Comments are closed.

Full Stack Development Articles

zen common ads

Get In Touch For Details! Request More Information

Post thumbnail

Constructors in JavaScript: 6 Uses Every Top Programmer Must Know

Mar 19, 2024 4 Min Read 472 Views

(Last Updated)

In the world of JavaScript programming, constructors play a crucial role. They are special functions that are used to create and initialize objects.

When an object is created using the new keyword, the constructor gets called, allowing you to set values for the object’s properties and perform any necessary initialization tasks.

In this comprehensive guide, we will explore the concept of constructors in JavaScript, understand how they work, and examine various examples and use cases.

Table of contents

  • What is a Constructor in JavaScript?
  • How Constructors in JavaScript Work?
  • How to use Constructors in JavaScript:
  • 1) Using the "this" Keyword in Constructors
  • 2) Creating Multiple Objects with Constructors
  • 3) Constructor with Parameters
  • 4) Constructor vs Object Literal
  • 5) Understanding Object Prototypes
  • 6) Built-in Constructors in JavaScript
  • Takeaways...
  • What are constructors in JavaScript?
  • What is the difference between a constructor and a class in JavaScript?
  • What are constructors in JavaScript used for?
  • Can we call multiple constructors?

A constructor is a special function in JavaScript that is used to create and initialize objects. It is typically defined within a class or an object blueprint. When a new object is created using the new keyword and a constructor function, the constructor gets invoked, and a new instance of the object is created.

The purpose of a constructor is to set the initial state of the object and define its properties and methods. It allows you to specify the values of the object’s properties when it is created, making it easier to work with and manipulate the object later on.

Must Read: Master JavaScript Frontend Roadmap: From Novice to Expert [2024]

Before we move to the next section, make sure that you are strong in the full-stack development basics. If not, consider enrolling for a professionally certified online full-stack web development course by a recognized institution that can also offer you an industry-grade certificate that boosts your resume.

When a constructor is called in JavaScript, several operations take place:

  • A new empty object is created.
  • The  this  keyword starts referring to the newly created object, making it the current instance object.
  • The properties and methods defined within the constructor are attached to the object.
  • The new object is returned as the result of the constructor call.

This sequence of operations ensures that a new object with the desired properties and behaviors is created and ready to be used.

Also Read: All About Loops in JavaScript: A Comprehensive Guide

Given below is the code to initialize two user instances as shown in the image above:

Let’s explore some examples of constructors in JavaScript to understand how they are used.

1) Using the “this” Keyword in Constructors

In a constructor, the this keyword refers to the newly created object. You can use the this keyword to define and assign values to the object’s properties. Here’s an example:

In the example above, the Car constructor takes three parameters: make , model , and year . The this keyword is used to assign the parameter values to the corresponding properties of the newly created myCar object.

By using the this keyword, you ensure that the values are specific to each instance of the Car object. If you were to create multiple car objects using the same constructor, each object would have its own unique set of property values.

Must Read: 4 Key Differences Between == and === Operators in JavaScript

Constructors are not limited to creating just a single object. You can create multiple objects using the same constructor. Each object will have its own set of properties and values. Here’s an example:

In the above example, the Circle constructor takes a radius parameter and defines a getArea method. The getArea method calculates and returns the area of the circle based on its radius.

By creating multiple circle objects using the new keyword and the Circle constructor, we can compute and output the areas of different circles. Each object has its own radius property and getArea method, ensuring that the calculations are specific to each circle.

Also Explore: Arrays in JavaScript: A Comprehensive Guide

MDN

Constructors in JavaScript can accept parameters, allowing you to pass values during object creation. This enables you to set different property values for each object based on the provided arguments.

Let’s consider an example of a Rectangle constructor:

In the above example, the Rectangle constructor takes two parameters: width and height . The constructor assigns the respective parameter values to the width and height properties of the newly created rectangle objects.

By creating multiple rectangles using the new keyword and the Rectangle constructor, we can calculate and output the areas of different rectangles. Each object has its own width and height properties, ensuring that the calculations are specific to each rectangle.

Must Explore: What is jQuery? A Key Concept You Should Know

In JavaScript, you have multiple ways to create objects. While constructors are useful for creating multiple objects with similar properties and behaviors, object literals are handy for creating single objects with specific properties.

Let’s compare the two approaches using an example:

In the example above, we have created three objects: person1 and person2 using the Person constructor, and person3 using an object literal.

The objects created with the constructor have similar properties and behaviors, allowing us to create multiple instances easily. On the other hand, the object created with the object literal approach is a single, standalone object with specific properties.

When deciding whether to use a constructor or an object literal, consider the specific needs of your program. Constructors are ideal when you need to create multiple objects with shared properties and behaviors. Object literals are suitable for creating single, independent objects with unique properties.

Also Explore: HTML Tutorial: A Comprehensive Guide for Web Development

In JavaScript, object prototypes play a significant role in defining shared properties and methods for objects created with a constructor. Prototypes allow objects to inherit properties and methods from a common prototype object.

Let’s consider an example of a Person constructor with a shared method defined in the prototype:

In the above example, the Person constructor creates a person object with name and age properties. The shared greet method is defined in the Person.prototype , allowing all instances of Person objects to access and invoke the method.

By defining methods in the prototype, you ensure that they are shared across all instances of the objects created with the constructor. This improves memory efficiency and allows you to add or modify shared behaviors easily.

JavaScript provides several built-in constructors that you can use to create objects with specific types and functionalities. However, it is generally recommended to use primitive data types where possible for better performance. Here are some examples of built-in constructors:

In the above examples, we create objects using the built-in constructors String , Number , Boolean , Array , and Date . These constructors allow us to work with string, number, boolean, array, and date objects, respectively.

While using these constructors is possible, it is generally recommended to use primitive data types directly, as they offer better performance and are simpler to work with.

If you want to learn more about programming with JavaScript and make a successful career out of it, then you must sign up for the Certified Full Stack Development Course , offered by GUVI, which gives you in-depth knowledge of the practical implementation of all frontend as well as backend development through various real-life FSD projects.

Takeaways…

Constructors in JavaScript are essential for creating and initializing objects. They provide a way to define object blueprints and set initial property values.

By using constructors, you can create multiple objects with shared properties and behaviors, pass parameters during object creation, and leverage prototypes for shared methods.

Understanding constructors enables you to build more robust and flexible applications. Whether you’re creating simple objects or complex data structures, constructors play a vital role in JavaScript programming.

Remember to use constructors wisely, considering the specific needs of your program.

Must Read: Variables and Data Types in JavaScript: A Complete Guide

Constructors in JavaScript are special functions used for initializing objects created with a class or constructor function.

The main difference between a constructor and a class in JavaScript is that a constructor is a function used to create and initialize objects, while a class is a blueprint for creating objects.

Constructors in JavaScript are used to set initial values, assign properties, and perform other setup tasks when creating objects.

In JavaScript, a class can have only one constructor, but you can call multiple constructors using techniques like function overloading or using factory functions.

Career transition

Author

About the Author

Jaishree Tomar

A recent CS Graduate with a quirk for writing and coding, a Data Science and Machine Learning enthusiast trying to pave my own way with tech. I have worked as a freelancer with a UK-based Digital Marketing firm writing various tech blogs, articles, and code snippets. Now, working as a Technical Writer at GUVI writing to my heart’s content!

Did you enjoy this article?

Recommended courses.

  • Career Programs
  • Micro Courses

thumbnail

Most Popular

certifiedBy

Java Full Stack Development Course

Available in

emi

EMI Options Available

placement

Placement Guidance

mentor

1:1 Mentor Doubt Clearing Sessions

next

MERN Full Stack Development

Thumbnail

ReactJs Project

Thumbnail

MEAN Stack Course

Thumbnail

Advanced JavaScript

Thumbnail

PHP with MySQL

Thumbnail

Spring Boot

Thumbnail

HTML CSS Project

Thumbnail

jQuery - Beginners to Advanced

Thumbnail

Schedule 1:1 free counselling

Similar Articles

Feature Image - Tips For Secure Coding Practices in Full Stack Development

By   Lukesh S

09 Apr, 2024

Feature Image - Top Backend as a Service (BaaS) Providers

By   Meghana D

Feature Image - Node.JS as Backend

08 Apr, 2024

Feature Image - Top Technologies to Learn for a Java Backend Developer

06 Apr, 2024

Feature Image - The Best Way To Learn Back-End Development

By   Jaishree Tomar

Non-tech to Tech, How difficult is that

By   Archana

04 Apr, 2024

Feature Image - Interaction Between Frontend and Backend

Introduction to HTML, CSS and JavaScript

  • Part I - HTML
  • What is HTML?
  • Building our First HTML Page
  • Creating Forms in HTML
  • HTML Tables
  • Part II - JavaScript
  • Writing Your First JavaScript Program
  • Primer on JavaScript
  • Events, Onload Event and JQuery
  • Processing Form Elements Using JQuery and Unobtrusive JavaScript
  • Functional Programming in JavaScript
  • Part III - CSS and Styling a Web Page
  • Web Page Header and Footer using CSS
  • Adding the form to the Page
  • Part IV - Object Oriented Programming in JavaScript
  • Why Use ECMA 5 as Basis?
  • Is JavaScript just Plain Weird?
  • Basic Objects in JavaScript

Constructor Functions and Prototype Objects in JavaScript

  • Scoping in JavaScript
  • A Simple JavaScript OOP Model
  • A JavaScript Object Model that Includes Encapsulation and Data Hiding
  • Unstructured Data

Related Books

The PHP Programming Language

The PHP Programming Language

TypeScript for Java Developers by CodeAhoy

TypeScript for Java Developers by CodeAhoy

The Little ASP.NET Core Book

The Little ASP.NET Core Book

Introduction to Networking

Introduction to Networking

An Introduction to libuv

An Introduction to libuv

Books / Introduction to HTML, CSS and JavaScript / Chapter 19

The purpose of this section is to continue to build the JavaScript Object Model. It will explain what a Constructor Function is, and how it can be used to create objects. It will show to define Constructor Functions to define how to build generic templates for creating objects, and how to use prototypes and prototype chains to add behavior easily to these object definitions.

Constructor Function and Object Creation

Property maps are a nice way to represent object properties and have many advantages over static class-based definitions of objects. But the way we have defined objects up to this point does not allow for default values, or for behaviors (functions) to be associated with the object without redefining the function for each object. JavaScript addresses these problems by allowing functions (called Constructor Functions) to build the object property maps. The JavaScript new operator is then used to set a variable to the property map created in the function.

To understand how this works, consider the following program fragment that creates two Map objects, mapA and mapB . This is accomplished by setting both variables to different object definitions. The entire definition for this object, including the functions, must be copied.

Program 91 - Creating two objects by setting them to different object literal values

In the code in Program 91 above, the function print has access to a variable this, which is just a property map (or object) associate with the object. The use of the this variable will be used to define objects from a common function.

The need to create two object definitions for the same object is inefficient and error prone. In JavaScript the ability to create a template for an object and use it to create objects is accomplished using a Constructor Function. A Constructor function is a function that constructs objects. It uses the this property map when the function is invoked, and builds the object that is to be used on the this object. The JavaScript new operator then makes the this property map accessible to assign to a variable.

The following program shows the use of a Constructor Function Map and the new operator to create the equivalent mapA and mapB variables from Program 86 above. The objects mapA and mapB are exactly equivalent to the ones from Program 82, including the fact that they each contain their own copy of the print function.

Program 92 - Using a Map Constructor Function

Note that all of the properties for both maps, including the functions, are stored separately. There are two property maps created, one for each variable reference. These property maps include two separate print functions, as each property map will have a variable referencing a different print function. How to make a single print function will be covered later in this chapter.

At this point, there are probably readers who want to equate a JavaScript Constructor Function with a Java class , and to equate the Java and JavaScript new operators. This is a completely wrong understanding of the new operator in the two languages. In Java a class is a template which includes functions and data, and the new operator creates an instance of that template. The Java new operator then calls a Java Constructor to initializes the variables in the constructed instance.

To re-emphasize, a JavaScript Constructor Function is not a template for a class that is instantiated. A Constructor Function is a function that is invoked, and when executed assigns properties, including functions, to a property map. The property map is then made available to a variable using the new operator. The new operator plays no part in constructing the object or how the function properties are called. It is as wrong to equate how a Java and JavaScript object are created as it is to equate how Java and JavaScript define and use objects. Going down that path will in the end only lead to confusion.

Passing parameters to a Constructor Function

The Constructor Function provided in the previous example is not really useful because only the default values for properties can be set when the function is called. To be useful the function needs to have parameters which can be used to set the properties. The simple answer to this problem would be to have a parameter to each value to be set, as in the following example.

Program 93 - Passing parameters to a Constructor Function

This solution of adding a parameter for each default value is not a good solution. What happens when a value for a parameter is not defined, implying that the default value should be used? The value is passed as null in the program above, but what if null is a valid value to set to the variable? JavaScript also allows objects to contain values that would not have a default. How are these set?

The solution used here is to pass an object (property map) to the JavaScript Constructor Function, with only the non-default properties in that parameter object. The following illustrates how to implement this solution with the Map Constructor. Note that not only is this code much shorter, to properly handles default values, and allows the object to have values that are not predefined with default values.

Program 94 - Using a Constructor Function to reconstruct an object

This example is the first where the true value and power of JavaScript objects and its object model as shown. But it is just the start of the amazing power of objects in JavaScript.

Constructor Functions and JSON

One nice feature of constructor functions is how nicely they work with JSON. Remember that when creating a JSON object, the functions are not serialized. Only the primitive data items are set in the JSON object. A map object serialized to JSON and then read back into the program will be missing the print function. The issue is how the print function can be added back to the object.

To add the print function back to the object, the JSON object can be passed to the Constructor Function. The object that will be returned from the constructor function add back the methods which were originally part of the object. This is shown below in the Program 95. In this example, a Map object, mapA , is created and serialized into a JSON object. This JSON object is then set to objA , which has all the fields of the mapA object, but is not a Map object and it does not have a print function defined. The objA object is then passed to the Map Constructor function, where the properties of objA are copied into a new mapB object. The print method can then be called on the mapB object.

Program 95 - Using a Constructor Function to reconstruct a JSON object

This ability to use JSON to store data, and to later pass those JSON objects to the Constructor Functions and reconstruct the original object, will be extensively used later.

Abstracting behavior and prototypes

This chapter so far has emphasized the fact that the functions that are part of an object are copied into the property map of every object. While storing these functions as data with each object allows for exceptions in which specific objects can have behavior that is different for special instances of the object, it is obviously inefficient. What is needed is a way to store the functions once and have them be accessed by all the objects constructed by a single Constructor Function.

This functionality should be implemented in a way consistent with the way the JavaScript language works, and this means using property maps (not class-based templates). A simple solution is to have Constructor Functions have a special property map associated with the function, and then have a link to the Constructor Function’s property map stored with each object to share properties across multiple objects. Then when a property, such as a function, is requested for an object, the object’s property map is searched for this property. If the property or function is not found in the object’s property map, the shared property map for the Constructor Function can then searched. Multiple shared property Maps can exist, and they can each be recursively searched in turn until either the property is found, or the end of the shared property maps is reached. This is shown below.

constructor assignment javascript

This recursive shared property map concept is implemented in JavaScript and is called prototypes .

Every function, not just Constructor functions, has associated with it a prototype object (property map) (Note: Unless a function is a Constructor Function, this prototype object is not used, but the function will still have prototype objects associated with them.)

To see how this prototype object is used, the construction of the JavaScript object with the new operator needs to be understood.

When the JavaScript new operator is invoked, it does two things.

  • First it sets the variable on the left-hand-side (lhs) of the equal sign to the this variable that was used in the Constructor Function.
  • Second a prototype variable (a link) in the object’s property map is set to point to the prototype object property map corresponding to the Constructor Function. The value of this link cannot be directly changed by the object but is accessed when a property is requested for the object that cannot be found in the objects property map.

The behavior of recursively searching property maps, described earlier, can now be implemented. When a function is requested, the property map for the individual object is searched. If the function is not found, the search continues in the prototype map of the Constructor Function. If it is still not found, the search continues until either the function is found, or the root of the tree, the Object prototype, is reached.

In the following example, the print method is moved from the individual objects, and stored in the Map protocol object. Now the two objects, MapA and MapB, both share the same print function.

Inheritance and Polymorphism

As I wrote the title to this section, I could just see the eyes rolling of a number of readers. Inheritance and polymorphism are always a problem in a class in Java/C#/C++/etc. Let me put everyone’s mind at ease. In JavaScript, if you understood prototypes from the last section, you already know these concepts in JavaScript.

Program 97 – Polymorphism in JavaScript

This changes the meaning of inherit from as used in Java and other class-based OOP languages. When discussing prototypes and JavaScript, the term inherit from means that the property map for the current object links to (inherits from) the prototype object’s property map, and the property maps are searched recursively for a property. This is, in a sense, how polymorphism is implemented in class-based languages, but it is so abstracted away that any sense of what is going on is lost to most programmers.

To summarize, polymorphism, or calling different methods which have the same name, in JavaScript means that the property maps are searched until the first occurrence of that property is found.

What is missing in this section is how to implement inheritance and composition delegation in JavaScript. There is a good reason for that. First, while the concept of inheritance is simple in JavaScript, changing the property map links is non-trivial; and until someone shows me a valid design using inheritance that cannot be implemented more easily and correctly using some other design mechanism, my advice is to not use inheritance. Thus, I never cover inheritance (other than interface inheritance, which is not the same as class inheritance) in any language.

As for compositional delegation, this is normally solved in JavaScript using Functional Programming. While I might be more inclined to describe how to implement delegation, as it is not that difficult, until a see a real-life case where it is an advantage over Functional Programming in JavaScript, I see no need to cover something that is at best useful in one-off situations.

JSON and prototype properties

What happens to the protocol chain when an object is serialized to JSON? When serializing an object, only the properties that can be externally represented are written to the JSON object. For the prototype variable (link to a Constructor Function prototype object) there is no way to know if the corresponding Constructor Function will exist when this JSON object is loaded into the new environment, so it must be dropped from the JSON definition.

But dropping the prototype link variable from the JSON object does not represent a problem. If the Constructor Function for the object is known, the appropriate Constructor Function can be called passing in the JSON object to reconstruct the original object, just as was done in Program 98. This is shown in the following program to reconstruct the prototype chain for Map objects.

Note : The protocol chain for a JSON object can be updated more simply by using the JavaScript setPrototypeOf function. Use of this function is, however, strongly discouraged. The setPrototypeOf function must change many structures in the program to optimize how prototype chains are optimized, and is a very expensive function to call. Also, any default code that is normally executed when constructing an object is not run. For these reasons, it is recommended that a new variable with the proper prototype constructor be created. This text will recommend that to create a new object, a correct Constructor Function be written that sets all default property values and saves all property values of the original object be created, and that Constructor Function be called using the JSON object.

Program 98 - Reconstructing the protocol chain for a JavaScript object

Finding the JavaScript Constructor Function in the DOM

Calling the correct Constructor Function to reconstruct the object works fine so long as the correct Constructor Function is known for the JSON object. But what if a number of different functions, created with different Constructor Functions, are stored externally, and the program does not know what Constructor Function corresponds to each JSON object?

Fortunately, there is an answer for this in JavaScript. All Constructor Functions are stored as lambda values in the DOM using the window property map. To retrieve and execute the Map Constructor Function using the object JSONObject can be done in the following line of code:

All that is needed to recreate the JSON object is the name of the Constructor Function, and that can be stored as a property in the JSON object itself. A strange looking name should be used so that it will not overlap with names the programmers might choose, so we will use the name “ __cfName ”. The new definition of the Map Constructor Function will now be the following:

Program 99 - Map Constructor Function setting the __cfName variable

Now that the name of the Constructor Function to call is known, the following function, getObjectFromJ can reconstruct any JSON object using the correct Constructor Function.

The following example shows how to use the getObject function on a JSON object that represents a Map.

Licenses and Attributions

Copyright (C) CodeAhoy. This book is licensed under Creative Commons Attribution- ShareAlike 4.0 International License

Original Content CC-BY-SA 4.0 International

  • This work is a derivative of "Programming for the Web: From Soup to Nuts: Implementing a complete GIS web page using HTML5, CSS, JavaScript, Node.js, MongoDB, and Open Layers." by Charles W. Kann III used under Creative Commons Attribution 4.0 License.

Other Content, as indicated:

  • Some excerpts in the Introductory chapter taken from "HTML" , Wikipedia, used under the Creative Commons Attribution-ShareAlike License 3.0.

Speak Your Mind Cancel reply

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Object() constructor

The Object() constructor turns the input into an object. Its behavior depends on the input's type.

Note: Object() can be called with or without new , but sometimes with different effects. See Return value .

Return value

When the Object() constructor itself is called or constructed, its return value is an object:

  • If the value is null or undefined , it creates and returns an empty object.
  • If the value is an object already, it returns the value.
  • Otherwise, it returns an object of a type that corresponds to the given value. For example, passing a BigInt primitive returns a BigInt wrapper object.

When Object() is constructed but new.target is not the Object constructor itself, the behavior is slightly different — it initializes a new object with new.target.prototype as its prototype. Any argument value is ignored. This may happen, for example, when Object() is implicitly called via super() in the constructor of a class that extends Object . In this case, even if you pass a number to super() , the this value inside the constructor does not become a Number instance.

Creating a new Object

Using object given undefined and null types.

The following examples store an empty Object object in o :

Obtaining wrapper objects for BigInt and Symbol

The BigInt() and Symbol() constructors throw an error when called with new , to prevent the common mistake of creating a wrapper object instead of the primitive value. The only way to create a wrapper object for these types is to call Object() with them:

Constructor, operator "new"

The regular {...} syntax allows us to create one object. But often we need to create many similar objects, like multiple users or menu items and so on.

That can be done using constructor functions and the "new" operator.

Constructor function

Constructor functions technically are regular functions. There are two conventions though:

  • They are named with capital letter first.
  • They should be executed only with "new" operator.

For instance:

When a function is executed with new , it does the following steps:

  • A new empty object is created and assigned to this .
  • The function body executes. Usually it modifies this , adds new properties to it.
  • The value of this is returned.

In other words, new User(...) does something like:

So let user = new User("Jack") gives the same result as:

Now if we want to create other users, we can call new User("Ann") , new User("Alice") and so on. Much shorter than using literals every time, and also easy to read.

That’s the main purpose of constructors – to implement reusable object creation code.

Let’s note once again – technically, any function (except arrow functions, as they don’t have this ) can be used as a constructor. It can be run with new , and it will execute the algorithm above. The “capital letter first” is a common agreement, to make it clear that a function is to be run with new .

If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:

This constructor can’t be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.

Constructor mode test: new.target

The syntax from this section is rarely used, skip it unless you want to know everything.

Inside a function, we can check whether it was called with new or without it, using a special new.target property.

It is undefined for regular calls and equals the function if called with new :

That can be used inside the function to know whether it was called with new , “in constructor mode”, or without it, “in regular mode”.

We can also make both new and regular calls to do the same, like this:

This approach is sometimes used in libraries to make the syntax more flexible. So that people may call the function with or without new , and it still works.

Probably not a good thing to use everywhere though, because omitting new makes it a bit less obvious what’s going on. With new we all know that the new object is being created.

Return from constructors

Usually, constructors do not have a return statement. Their task is to write all necessary stuff into this , and it automatically becomes the result.

But if there is a return statement, then the rule is simple:

  • If return is called with an object, then the object is returned instead of this .
  • If return is called with a primitive, it’s ignored.

In other words, return with an object returns that object, in all other cases this is returned.

For instance, here return overrides this by returning an object:

And here’s an example with an empty return (or we could place a primitive after it, doesn’t matter):

Usually constructors don’t have a return statement. Here we mention the special behavior with returning objects mainly for the sake of completeness.

By the way, we can omit parentheses after new :

Omitting parentheses here is not considered a “good style”, but the syntax is permitted by specification.

Methods in constructor

Using constructor functions to create objects gives a great deal of flexibility. The constructor function may have parameters that define how to construct the object, and what to put in it.

Of course, we can add to this not only properties, but methods as well.

For instance, new User(name) below creates an object with the given name and the method sayHi :

To create complex objects, there’s a more advanced syntax, classes , that we’ll cover later.

  • Constructor functions or, briefly, constructors, are regular functions, but there’s a common agreement to name them with capital letter first.
  • Constructor functions should only be called using new . Such a call implies a creation of empty this at the start and returning the populated one at the end.

We can use constructor functions to make multiple similar objects.

JavaScript provides constructor functions for many built-in language objects: like Date for dates, Set for sets and others that we plan to study.

In this chapter we only cover the basics about objects and constructors. They are essential for learning more about data types and functions in the next chapters.

After we learn that, we return to objects and cover them in-depth in the chapters Prototypes, inheritance and Classes .

Two functions – one object

Is it possible to create functions A and B so that new A() == new B() ?

If it is, then provide an example of their code.

Yes, it’s possible.

If a function returns an object then new returns it instead of this .

So they can, for instance, return the same externally defined object obj :

Create new Calculator

Create a constructor function Calculator that creates objects with 3 methods:

  • read() prompts for two values and saves them as object properties with names a and b respectively.
  • sum() returns the sum of these properties.
  • mul() returns the multiplication product of these properties.

Run the demo

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Create new Accumulator

Create a constructor function Accumulator(startingValue) .

Object that it creates should:

  • Store the “current value” in the property value . The starting value is set to the argument of the constructor startingValue .
  • The read() method should use prompt to read a new number and add it to value .

In other words, the value property is the sum of all user-entered values with the initial value startingValue .

Here’s the demo of the code:

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

JS Reference

Html events, html objects, other references, javascript class constructor.

Create a Car class, and then create an object called "mycar" based on the Car class:

Try it Yourself »

More "Try it Yourself" examples below.

Description

The constructor() method is a special method for creating and initializing objects created within a class.

Note: A class cannot have more than one constructor() method. This will throw a SyntaxError .

You can use the super() method to call the constructor of a parent class (see "More Examples" below).

Browser Support

constructor() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers since June 2017:

constructor() is not supported in Internet Explorer.

Technical Details

More examples.

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

Create a class named "Model" which will inherit the methods from the "Car" class:

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and get access to the parent's properties and methods.

Related Pages

JavaScript Tutorial: JavaScript Classes

JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)

JavaScript Reference: The extends Keyword

JavaScript Reference: The super Keyword

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. Constructor in JavaScript

    constructor assignment javascript

  2. How to use JavaScript Classes, Class Constructor and Class Inheritence?

    constructor assignment javascript

  3. Constructor Method in JavaScript

    constructor assignment javascript

  4. How to use JavaScript Classes, Class Constructor and Class Inheritence?

    constructor assignment javascript

  5. Constructor assignment of field variables in TypeScript

    constructor assignment javascript

  6. Bundle your JavaScript · System Designer

    constructor assignment javascript

VIDEO

  1. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  2. JS Coding Assignment-2

  3. javascript 031309 constructor

  4. 1st Assignment JavaScript/ Type script in a governor house onsite class

  5. javascript 031409 constructor

  6. constructor function javascript newkeyword #coding #devopsintelugu #javascript #html

COMMENTS

  1. constructor

    Using new on a class goes through the following steps: (If it's a derived class) The constructor body before the super() call is evaluated. This part should not access this because it's not yet initialized. (If it's a derived class) The super() call is evaluated, which initializes the parent class through the same process.; The current class's fields are initialized.

  2. JavaScript Constructors

    Object Types (Blueprints) (Classes) The examples from the previous chapters are limited. They only create single objects. Sometimes we need a "blueprint" for creating many objects of the same "type".The way to create an "object type", is to use an object constructor function.. In the example above, function Person() is an object constructor function. ...

  3. JavaScript Constructor Function

    Introduction to JavaScript constructor functions. In the JavaScript objects tutorial, you learned how to use the object literal syntax to create a new object. For example, the following creates a new person object with two properties firstName and lastName: firstName: 'John' , lastName: 'Doe'. In practice, you often need to create many similar ...

  4. JavaScript Constructor Function (with Examples)

    In JavaScript, a constructor function is used to create objects. For example, this.name = 'John', this.age = 23. // create an object const person = new Person(); In the above example, function Person() is an object constructor function. To create an object from a constructor function, we use the new keyword.

  5. An Easy Guide To Understanding Constructors In JavaScript

    2. Functions, Constructors And The new Operator. In section 1 we learned that when the Person constructor, (or any other constructor) is invoked without the new operator it is invoked as a regular JavaScript function. In this section, we will elaborate on this with code examples. Kindly consider the code below.

  6. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  7. A Visual Guide to JavaScript Constructor / Prototype Pattern

    The combination of the constructor and prototype patterns is the most common way to define custom types in ES5. In this pattern: The constructor pattern defines the object properties. The prototype pattern defines the object methods. By using this pattern, all objects of the custom type share the methods defined in the prototype.

  8. Getting Started With JavaScript Constructor Functions

    Then, inside the constructor, you can use these parameters to assign those properties with provided values. This will allow you to create objects with different values for name and age properties. // Create constructor function // that accepts two parameters, "name" and "age": function Person(name, age) { // Define properties and assign them ...

  9. Javascript Object Constructors

    The function Car() is an object constructor function. Best practices for Javascript object constructors are: The new keyword must be used to instantiate an object. Constructor names begin with a capital letter. The constructor has three parts, two of which are done for you by Javascript: the assignment of this to the object address and ...

  10. The JavaScript "this" Keyword Deep Dive: Constructor Functions

    When you instantiate a JavaScript constructor function, the JavaScript "this" keyword refers to the instance of the constructor. We've also created a constructor function named "Foo". When we instantiate Foo, we assign that instantiation to the variable: "bar". In other words, the variable "bar" becomes an instance of "Foo".

  11. Constructors in JavaScript: 6 Uses Every Top Programmer Must Know

    1) Using the "this" Keyword in Constructors. In a constructor, the this keyword refers to the newly created object. You can use the this keyword to define and assign values to the object's properties. Here's an example: // Constructor. function Carss(making, model, year) {. this.make = making; this.model = model;

  12. javascript

    To have defaults, you can just set up a default object, or assign them outside the constructor as class properties. EDIT To T.J. Crowder's point, technically anything passed in while using Object.assign() will be added to your object, which could be harmful in a number of ways. I have added a way to strip the config object to only contain a set ...

  13. javascript

    class Polygon { constructor({height, width}) { Object.assign(this, arguments[0]); } } Though, creating this object will require creating a "config" object which, depending on your view, either adding clutter to the code or making it more readable:

  14. Constructor Functions and Prototype Objects in JavaScript

    In JavaScript the ability to create a template for an object and use it to create objects is accomplished using a Constructor Function. A Constructor function is a function that constructs objects. It uses the this property map when the function is invoked, and builds the object that is to be used on the this object.

  15. Object() constructor

    When the Object() constructor itself is called or constructed, its return value is an object: If the value is null or undefined, it creates and returns an empty object. If the value is an object already, it returns the value. Otherwise, it returns an object of a type that corresponds to the given value. For example, passing a BigInt primitive ...

  16. Constructor, operator "new"

    Create a constructor function Accumulator(startingValue).. Object that it creates should: Store the "current value" in the property value.The starting value is set to the argument of the constructor startingValue.; The read() method should use prompt to read a new number and add it to value.; In other words, the value property is the sum of all user-entered values with the initial value ...

  17. JavaScript Class constructor Method

    Description. The constructor() method is a special method for creating and initializing objects created within a class. The constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty ...

  18. Is it possible to destructure instance/member variables in a JavaScript

    Is it possible to use destructuring assignment in a JavaScript class' constructor to assign the instance variables similar to how you can do it to normal variables? The following example works: var options = {one: 1, two: 2}; var {one, two} = options; console.log(one) //=> 1 console.log(two) //=> 2

  19. Assigning value of 'this' in JavaScript constructor

    this is a reserved word in JavaScript and refers to the read-only context variable. You cannot reassign it. If there is no reason you can't simply continue to use the contex variable, do that. If you need to create a local variable, then name it something else: var that = contex; edited Apr 8, 2013 at 21:13.