Javascript new operator examples

The javaScript new operator is something that will come up in the occasional code example here and there, knowing what it does, and being aware of the many other subjects that branch off from it is a must for any javaScript developer. In this post I will be touching base with some examples that make use of the new operator, and some related subjects to the use of the new operator.

1 - javaScript new operator a basic example.

The new operator is used in conjunction with a constructor function to create an instance of that constructor function. There are many such constructor functions built into core javaScript itself such as the Date constructor that can be used to create an instance of a javaScript Date Object.

1
2
3
let d = new Date(2017,3,6,10,5);
console.log( d.getDate() ); // 6

In this example the d variable is an instance of Date that was created using the new operator with the Date constructor function. Once I have my instance of Date I can use any of the prototype methods of the Date constructor, as well as any additional methods that may be in the prototype chain as well, such as Date.getDate

2 - Creating a Constructor for use with the new operator in javaScript

To create my own constructor function I just need to create a function and in the body of the constructor function or any prototype method use the this keyword as a way to refer to any property that is to be an OwnProperty of the instance of this constructor when created using the new operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let Guy = function (x, y) {
this.x = x;
this.y = y;
};
Guy.prototype.move = function (dx, dy) {
this.x += dx;
this.y += dy;
};
let g = new Guy(10, 12);
g.move(-5, 7);
console.log(g.x,g.y); // 5 19

If I where to to call this method without using the new operator the method would return the undefined value which is the default value that is return when a function is called in that manner without the use of the new keyword.