Dot Net For All

Learning JavaScript – Classes and Properties with Examples

In my previous posts I have discussed about the datatypes, functions and this keyword in javascriptIn this article I will discuss about the anonymous type,  class, properties and how we can achieve encapsulation in JavaScript with code examples.

Class in JavaScript

There are  no classes in JavaScript and we have to use the functions only to create the semantic of class. In the below figure I have created a function named Student which is assigning the parameters passed to it to the local variables. It is the only place where we have to adhere to the pascal casing to define the function.

This type of deceleration of object is known as constructor syntax. Here we are using the new keyword to find the function which is just following the keyword (Student in our case) and return the state of the object which contain the properties and its values.

The public properties in the class need to be declared with the ‘this’ keyword.

We can now get any of the property of this class by accessing the property of this instance as shown below.

alert(student.firstName);  //Vikram

Adding member function to the class

We need to add functions to have some behaviour which will work on the data of the class. We can add function to the class as shown in the code below

 function Student(fName, lName) {
    this.fName = fName;
    this.lName = lName;
    this.transfer = function (transferTo) {
        alert( this.fName + " transferred to "  + transferTo);
    };
}

I have added a function named transfer to the Student class and added the functionality to it. We can create an instance of the Student class and call the function as shown below.

var student = new Student("Raj", "Singh");
student.transfer("sixthStandard");

Encapsulation in Javascript

We do not have notion of public and private members in JavaScript. But we can encapsulate a variable by using the scope technique which I have discussed here in one of my article.
Since I have created the public properties by using the ‘this’ keyword like fName and lName for the Student class in the previous code snippet but if we want to create a private variable we should not use this keyword, we have to just use the var keyword as shown in the below code.

 function Student(fName, lName) {
    this.fName = fName;
    this.lName = lName;
	
    var optionalSubject = "physics";
	
    this.transfer = function (transferTo) {
        alert( this.fName + " transferred to "  + transferTo + " opted for " + optionalSubject);
    };
}

Properties in Javascript

By adding this keyword to the objects we can add publicly accessible fields to the classes. There can be cases when we want to add the read only or write only fields to the classes or to add some arbitrary code while setting value to the the fields. In this case the properties come to the rescue.

function Student(fName, lName) { 
    var _optionalSubject = "phyics";
    Object.defineProperty(this, "optionalSubject", {
        get: function () {
            return _optionalSubject;
        }
    })   
}

In the code snippet above I have created a read only property named optionalSubject by using the defineProperty method of Object. The _optionalSubject is the variable which this property is encapsulating.

I can also add the set function to this code as shown below which can be used to write the local variable and hence making the property to read and write.

function Student() {    

    var _optionalSubject = "phyics";

    Object.defineProperty(this, "optionalSubject", {
        get: function () {
            return _optionalSubject;
        },
        set: function (value) {
            _optionalSubject = value;          
        }
    })   
}

Creating Anonymous Types in javaScript

Just like C# we have concept of anonymous(dynamic) object in Javascript.

var student = {
    firstName: "Vikram",
    lastName: "Chaudhary",
    "Studying In": "2nd Std",
    address: {
        addressLine: "Indira Nagar",
        city: "Bangalore"
    }
}

As we can see from the above code I have created an student anonymous type which contains properties in name-value pair format. Here you can see that that we can embed the name also in the double quotes if it contain some special characters such as space in our case. Also there is one more type(address) embedded in our parent type.

We can access these name-value pair in JavaScript by using the dot syntax or the bracket syntax as shown below.

 var firstName = student.firstName;
 var firstName1 = student["firstName"];

But if we dealing with the property which have special character in its name in that case we should use the bracket syntax as shown below

var studyingIn = student[“Studying In”];

Since the JavaScript is loosely coupled language that is why we can add properties and functions to these dynamic objects at the fly as shown in the below code.

student.classTeacher = "Ravi Kumar";
student.TransferToOtherSchool = function(){
alert("transfer the student");
};

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview