Seven Ways of Creating Objects in JavaScript for C# Developers
As a C# developer building ASP.NET web applications you create classes and
then use their objects in your application. In JavaScript, however, there are
multiple ways to create objects. This article gives you a quick overview of
these available options with an example of each.
In C# usually creating objects involves two steps - create a class and then
create object of that class. In JavaScript you don't formally create
classes (unless you are using ES6 class keyword discussed later in this article)
like you do in C# sense. Instead, you directly create objects. Moreover,
JavaScript functions are object themselves and you can create objects of a
function.
If you are a beginner in JavaScript driven development it is worthwhile to note
that
C# is a class based language whereas JavaScript is a prototype based language.
You may read more about these two approaches
here and here.
Without going into too much details let's go straight to the syntax of
various object creation options. To test these fragments of code you can create
a new ASP.NET MVC or ASP.NET Core application and add them to a view file.
Visual Studio also helps you by presenting the IntelliSense for object
properties and methods.
1. Object literals using { }
var emp1 = {};
emp1.firstName = "Nancy";
emp1.lastName = "Davolio";
emp1.showName = function () {
alert(this.firstName + " " + this.lastName);
};
emp1.showName();
In this way of creating objects you create an object using object literal or
object initializer syntax. The empty curly brackets indicate that a new object
has been created. Once created you can add members to the object using
object-property syntax. This code should look familiar to you since C# also uses
the same convention for member assignments. The above code adds two members
firstName and lastName to the object and assigns them some value. Then it adds
the showName() function to the object. Notice how the showName() function makes
use of this keyword to access firstName and lastName.
Once the members are added to the object the code invokes the showName()
method on emp1. If you run this code you will see an alert dialog showing the
name Nancy Davolio.
2. Object literals using { key : value }
var emp2 = {
"firstName": "Nancy",
"lastName": "Davolio",
"showName": function () {
alert(this.firstName + " " + this.lastName);
}
};
emp2.showName();
The above way of creating object is a variant of object literal syntax. It
specifies object members and their values inside the curly brackets as key-value
pairs. A member and its value are delimited using colon (:) character. The
object created using option 1 earlier and 2 both finally mean the same thing.
You can confirm that by calling the showName() on emp2.
3. Using new Object()
var emp3 = new Object();
emp3.firstName = "Nancy";
emp3.lastName = "Davolio";
emp3.showName = function () {
alert(this.firstName + " " + this.lastName);
};
emp3.showName();
This time we use a bit readable and more verbose way of creating an object.
The new keyword is used to create a new object based on inbuilt Object. Member
and then added to the newly create object as before.
4. Using Object.create()
var emp4 = Object.create(null);
emp4.firstName = "Nancy";
emp4.lastName = "Davolio";
emp4.showName = function () {
alert(this.firstName + " " + this.lastName);
};
emp4.showName();
A variation of 3 above is Object.create() method. The create() method creates
a new object based on the prototype of the supplied object. In this case we
supply null so it's pretty much the same as 3. This syntax is handy if you have
an object with default values and wish to create multiple objects based on that
prototype.
5. Using function constructor
function Employee(fname,lname) {
this.firstName = fname;
this.lastName = lname;
this.showName = function () {
alert(this.firstName + " " + this.lastName);
};
}
var emp5 = new Employee("Nancy", "Davolio");
emp5.showName();
As mentioned earlier JavaScript functions are objects themselves and can have
what is known as a constructor function. In this example the constructor accepts
two parameters fname and lname. The constructor code then assigns their values
to the firstName and lastName members. The showName() function has also been
defined. Once the function constructor is created you create object of that
function using new keyword. Notice how values of fname and lname are passed to
the constructor while creating the object. Also notice that the function name
uses capital E as against the camel case convention used by members.
6. Using anonymous function
var emp6 = new function () {
this.firstName = "Nancy";
this.lastName = "Davolio";
this.showName = function () {
alert(this.firstName + " " + this.lastName);
};
}
emp6.showName();
This approach does two things in one go. Firstly, it creates an anonymous
constructor function and secondly, it calls new on it to create its object.
7. Using ES6 class keyword
class Employee {
constructor(fname, lname) {
this._firstName = fname;
this._lastName = lname;
}
get firstName() {
return this._firstName;
}
set firstName(value) {
this._firstName = value;
}
get lastName() {
return this._lastName;
}
set lastName(value) {
this._lastName = value;
}
showName() {
alert(this.firstName + " " + this.lastName);
}
}
var emp7 = new Employee("Nancy", "Davolio");
emp7.showName();
emp7.firstName = "Andrew";
emp7.showName();
The above code shows ES6 way of creating objects. First we define a class and
then we create objects of the class just defined. Remember that the class
keyword is just a syntactical sugar added by ES6 to make developer's life easy.
Behind the curtains it still uses the prototype based approach of creating
objects.
The the above code we create a class called Employee. The constructor of the
class initializes two member variables _firstName and _lastName. Then a series
of getters and setters is defined that wraps the _firstName and _lastName
variables. The showName() function is also defined and uses the getters to show
the values.
Once the Employee class is created the code proceeds to create its object
using the new keyword. Initial values of firstName and lastName are passed to
the constructor.
To read more about object creation and how to work with objects in JavaScript
go
here.
That's it for now ! Keep coding !!