Tutorials References Menu

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Events JS Strings JS String Methods JS String Search JS Numbers JS Number Methods JS Arrays JS Array Methods JS Array Sort JS Array Iteration JS Array Const JS Dates JS Date Formats JS Date Get Methods JS Date Set Methods JS Math JS Random JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop For In JS Loop For Of JS Loop While JS Break JS Typeof JS Type Conversion JS Bitwise JS RegExp JS Errors JS Scope JS Hoisting JS Strict Mode JS this Keyword JS Arrow Function JS Classes JS JSON JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words

JS Objects

Object Definitions Object Properties Object Methods Object Display Object Accessors Object Constructors Object Prototypes Object Reference Object Map() Object Set()

JS Functions

Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

JS Classes

Class Intro Class Inheritance Class Static

JS Async

JS Callbacks JS Asynchronous JS Promises JS Async/Await

JS Versions

JS Versions JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS IE / Edge JS History

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM Forms DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS Web APIs

Web API Intro Web Forms API Web History API Web Storage API Web Worker API Web Fetch API Web Geolocation API

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor

JS References

JavaScript Objects HTML DOM Objects


JavaScript Object Constructors


Example

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}
Try it yourself »

It is considered good practice to name constructor functions with an upper-case first letter.


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.

Objects of the same type are created by calling the constructor function with the new keyword:

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
Try it yourself »


The this Keyword

In JavaScript, the thing called this is the object that "owns" the code.

The value of this, when used in an object, is the object itself.

In a constructor function this does not have a value. It is a substitute for the new object. The value of this will become the new object when a new object is created.

Note that this is not a variable. It is a keyword. You cannot change the value of this.


Adding a Property to an Object

Adding a new property to an existing object is easy:

Example

myFather.nationality = "English";
Try it Yourself »

The property will be added to myFather. Not to myMother. (Not to any other person objects).


Adding a Method to an Object

Adding a new method to an existing object is easy:

Example

myFather.name = function () {
  return this.firstName + " " + this.lastName;
};
Try it Yourself »

The method will be added to myFather. Not to myMother. (Not to any other person objects).


Adding a Property to a Constructor

You cannot add a new property to an object constructor the same way you add a new property to an existing object:

Example

Person.nationality = "English";
Try it Yourself »

To add a new property to a constructor, you must add it to the constructor function:

Example

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.nationality = "English";
}
Try it Yourself »

This way object properties can have default values.


Adding a Method to a Constructor

Your constructor function can also define methods:

Example

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.name = function() {
    return this.firstName + " " + this.lastName;
  };
}
Try it Yourself »

You cannot add a new method to an object constructor the same way you add a new method to an existing object.

Adding methods to an object constructor must be done inside the constructor function:

Example

function Person(firstName, lastName, age, eyeColor) {
  this.firstName = firstName; 
  this.lastName = lastName;
  this.age = age;
  this.eyeColor = eyeColor;
  this.changeName = function (name) {
    this.lastName = name;
  };
}

The changeName() function assigns the value of name to the person's lastName property.

Now You Can Try:

myMother.changeName("Doe");
Try it Yourself »

JavaScript knows which person you are talking about by "substituting" this with myMother.


Built-in JavaScript Constructors

JavaScript has built-in constructors for native objects:

new String()    // A new String object
new Number()    // A new Number object
new Boolean()   // A new Boolean object
new Object()    // A new Object object
new Array()     // A new Array object
new RegExp()    // A new RegExp object
new Function()  // A new Function object
new Date()      // A new Date object
Try it Yourself »

The Math() object is not in the list. Math is a global object. The new keyword cannot be used on Math.


Did You Know?

As you can see above, JavaScript has object versions of the primitive data types String, Number, and Boolean. But there is no reason to create complex objects. Primitive values are much faster:

Use string literals "" instead of new String().

Use number literals 50 instead of new Number().

Use boolean literals true / false instead of new Boolean().

Use object literals {} instead of new Object().

Use array literals [] instead of new Array().

Use pattern literals /()/ instead of new RegExp().

Use function expressions () {} instead of new Function().

Example

let x1 = "";             // new primitive string
let x2 = 0;              // new primitive number
let x3 = false;          // new primitive boolean

const x4 = {};           // new Object object
const x5 = [];           // new Array object
const x6 = /()/          // new RegExp object
const x7 = function(){}; // new function
Try it Yourself »

String Objects

Normally, strings are created as primitives: firstName = "John"

But strings can also be created as objects using the new keyword:
firstName = new String("John")

Learn why strings should not be created as object in the chapter JS Strings.


Number Objects

Normally, numbers are created as primitives: x = 30

But numbers can also be created as objects using the new keyword:
x = new Number(30)

Learn why numbers should not be created as object in the chapter JS Numbers.


Boolean Objects

Normally, booleans are created as primitives: x = false

But booleans can also be created as objects using the new keyword:
x = new Boolean(false)

Learn why booleans should not be created as object in the chapter JS Booleans.