Various ways to Create custom objects in JavaScript

Hi All,

Many developers still put their data at client side in multiple variables and some times it becomes very tough to manage them. If we store the data in object format then it becomes very easy to manage and control it. We can have similar model as we use at server side, it provides consistency of the data model in our application.

So today we’ll see various ways to store the data in Object format at Client side.

A Simple way:

We can create a normal object and can encapsulate related data in a single object. To create  a simple object, you just need to assign a variable with new Object() and create the properties according to our requirement and assign the values as

 var person = new Object();
 person.FirstName = "Brij";
 person.LastName = "Mishra";
 person.Age = 27;

This is a simple object with few properties like FirstName, LastName and Age. You can read the object as

function displayObject() {
      alert(person.FirstName + " " + person.LastName);
      alert("Age: " + person.Age);
}

Here as you can see it is an object which contains the details of an person but here we didn’t define any class (as we do in C#) then we create an object assign some values in that. But we just created a object and created properties on the fly. Now obviously, while reading the object, you  might not get any intellisense on some editor and we need to remember the name of the properties. And if we wrongly typed the property name then we’ll get an error at run time.

Because JavaScript is loosely coupled language. There is no way if we create similar object and check whether they are similar type of object. Also it is impossible to identify  the object that you are using is actually of what type.

But there are more standard ways to Create a Type. We’ll discuss in coming section. First, we are going to discuss

Closure
Closure is function that encapsulate a class. Actually closure is not a normal function but it contains other functions and you can say it is a nested function. Inner functions actually constitutes its properties and methods. It provides an elegant way to create multiple instances of a type like person. It provides exactly similar behavior like class and object. Let’s create a closure

        function Person(fisrtName, lastName, age) {
            var _firstName = fisrtName;
            var _lastName = lastName;
            var _age = age;

            this.set_FirstName = function (fisrtName) {
                _firstName = fisrtName;
            }
            this.get_FirstName = function () {
                return _firstName;
            }
            this.set_LastName = function (lastName) {
                _lastName = lastName;
            }
            this.get_LastName = function () {
                return _lastName;
            }
            this.set_Age = function (age) {
                _age = age;
            }
            this.get_Age = function () {
                return _age;
            }
        }

Now let’s use the person and person instantiate it. As you can see that it is taking three parameters, fisrtName, lastName and age. So you need pass the values while instantiating it. Using it, you can create an instance similar like C# as

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see, How I created instance. I have created a setter and getter to set and get the properties.

Lets’s discuss another way.

Prototype:

Prototypes provides another way to create custom objects in JavaScript. Every JavaScript object has public prototype property . This actually exposes the public interface of the object. Using this feature, we can add some public properties and methods to a JavaScript object. Let’s see it with example

        Person = function (firstName, lastName, age) {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;

            Person.prototype.set_FirstName = function (firstName) {
                this._firstName = firstName;
            }
            Person.prototype.get_FirstName = function () {
                return this._firstName;
            }
            Person.prototype.set_LastName = function (lastName) {
                this._lastName = lastName;
            }
            Person.prototype.get_LastName = function () {
                return this._lastName;
            }
            Person.prototype.set_Age = function (age) {
                this._age = age;
            }
            Person.prototype.get_Age = function () {
                return this._age;
            }
        }

So you can see that person is assigned to a function which is actually also a nested function but it is uses prototype property of an object. Lets instantiate it and check it.

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see that this also is used in the similar way as Closure.
So what are the benefits of prototypes over closure. There are many..

  • Prototypes provide better support for Intellisense and debugging.
  • Prototypes also provide better performance in several browsers.
  • Prototypes support reflection and that’s why used a lot in ASP.NET AJAX.
  • Closure does not create an instance, it just specialized members to your object. instanceof does not work with Closure. While Prototype configured once then copied to every instance created using new.

Hope you all like it.

Cheers,
Brij

Object vs ref Object : Passing a reference type using ref keyword

In this post, I am going to talk about ref keyword in C#. You all must be knowing the basic use of this keyword. But for them who are new to this keyword or C#, will explain the basics.

ref keyword is used to pass the parameter by reference. It means the parameter references the same memory location as the original variable.

As we know that there are two type of variable in C#. One is Value type and other is Reference type. Whenever a value type variable is passed to a method, a copy that variable is created and passed to the method. So let’s see it pictorially

Passed by valueSo when the variable is updated in the called method, then initial variable is not updated but the copy variable gets updated.

Now let’s pass the parameter using ref keyword. So when we pass a value type variable using ref keyword the reference of the variable is passed and both variable names points to same memory location. So when the variable is updated it is available in both method. It can be depicted pictorially as

Pass value using refTill now we passed the value type variable. But when we send other type (reference type) variable to the method the reference is passed so when we update the object in the called method, the updated object gets available to both the method. let’s see the example

For this example,I used an instance of Class type

Typeand the example is

refLet’s come to the real question. What if we pass the instance using ref keyword. When the instance is itself a reference type then what else we get from it. Or they exactly same? Let’s see by example

refref1But if we see the above example, then we get the difference that now variable name points the reference of the reference variable name. When we update the object it updates the same memory location as earlier. By seeing the above example, it seems that there is no difference between passing the reference type variable normally and by ref keyword. But Wait !! Let’s see the screenshot

refref12Now when the UpdateName method get’s executed then what will happen. Let’s see this

refref2

So here after execution of UpdateName both variable name and myName points to null and now the object is available in memory but not accessible from any variable.

But if we pass the object without ref keyword in same method then

ref2So here variable name points to null but myName still points to that object and object is accessible.

So it means as long as we update the object by updating it’s property method etc.,it is same in both case but when we play with the variable name then it makes a difference as we have seen in the above example.

So next time when someone asks that difference by passing the a reference using ref keyword or without ref keyword then you can explain it.

Happy learning!!

Regards,
Brij

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

Hello All,

Garbage Collector is one the basic concepts in .NET framework and ironically one of most misunderstood concepts as well. Also, It is also one of the most asked interview questions. To understand the whole concept, one need to understand Object creation and it’s life cycle life cycle and memory management from the application point of view.

I am going to post a series of videos on Garbage Collector and hope this will help you in learning the basics of Garbage Collector. In my first video, I have talked on Object creation and about it’s life cycle.

Hope you’ll enjoy the video and don’t forget to share your feedback.

Cheers,
Brij