Broad Network


Creating ECMAScript Objects by Constructor Function

Creating JavaScript Objects by Constructor Function

Forward: In this article I show you how to create JavaScript objects using the constructor function.

By: Chrysanthus Date Published: 9 Aug 2012

Introduction

The aim of this article is to quickly make you understand the meaning of Programming Objects (OOP) and how to create them in JavaScript. I assume in this article that you know the meaning of variables and functions in JavaScript, but you might not have understood JavaScript objects. There are three ways of creating JavaScript objects and in this article I show you the one that is indicated by the title (of this article). Let us start.

Note: If you cannot see the code or if you think anything is missing (broken link), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what has been typed.

Variables, Functions and Objects in JavaScript
Let us look at two variables and a function. The two variables hold two numbers. The function adds the two numbers. These are the two variables and the function:

        <script type="text/javascript">
         var num1 = 5;
         var num2 = 8;
         function add ()
                {
                 answer = num1 + num2;
                 return answer;
                }

         var result = add();
         alert(result);
        </script>

As you can see in the code, there are two variables. The function adds the values of the two variables, and returns the answer. Below in the code, the function is called, and the return value is assigned to a new variable, result. The last statement alerts the result.

Now in programming (in a program code) you would find some functions that work with certain variables, such that if you remove one of the variables, the rest of the variables and the functions will not be very useful; if you remove one of the functions, the rest of the functions and the variables will not be very useful. In other words, the variables and functions in question form a set. The above group of statements is such a set. Would it not be nice if we had such a set in one unit? In fact, many modern programs, have such a set in one unit called an object. Many modern computer languages have each, its own syntax for creating an object. JavaScript has three ways of doing this and in this article we learn one of the ways.

Properties and Methods
A programming object fundamentally has what is called properties and methods. This is not a big deal. In the above script we have one function, which works with two variables. If we are to make this “set”, an object, then the variables would become the properties and the function would become the method. You can have more than one method in an object, just as you can have more than one property. As you can see it is not a big deal, all you have to do is to know the syntax that will make the variables, properties and the functions, methods.

The Constructor Function
The constructor function is the conventional function. The constructor function can be changed into an object. As an object, in its simplest form, it has just properties and methods. The reserved word, “this” is used inside the function to refer to the function. The reserved “this” word used in the function makes the function a prototypical object (see explanation below).

Creating the Prototypical Object
The prototypical object for the above set (two variables and one function) is in the following code:

        <script type="text/javascript">
            function theObject()
                {
                    this.num1 = 5;
                    this.num2 = 8;
                    this.add  = function ()
                                    {
                                        answer = this.num1 + this.num2;
                                        return answer;
                                    }
                }

            result = myObject.add();

            alert(result);

        </script>

The first statement in the code is the constructor function. The name of the constructor function is theObject. Inside the function, you have two properties and one method. The two properties begin with the reserved word, “this” and the method, also begins with the reserved word this. In this way, the constructor function is our prototypical object. In any prototypical object any property or method declaration begins with the reserved word, “this”.

In the constructor function, the name of the first property is, num1. In between this name and the reserved word, “this” is a dot. All properties are declared like so. This first property represents the first variable we have in the first code above. The property is assigned the value, 5. The name of the second property is, num2 and it is assigned the value, 8. This second property represents the second variable in the first code above. Our aim here is to have a prototypical object that will do the same work as the two variables and one function in the first code.

Next in the constructor function, you have the declaration and definition of the method. The declaration part is on the left of the assignment operator and the definition part is on the right of the assignment operator. This method represents the function of the first code above. The declaration part begins with the reserved word, “this”, followed by a dot, and then the name of the method. You are the one to choose the name of the method. Immediately after the name of the method, you do not have the () brackets.

Let us now look at the definition of the function. You have the function operator (word), “function”. This is followed by the () brackets. These brackets can have parameters. After that you have the curly braces, {}. Inside the curly braces you have the statements for the method definition. In these statements, you precede any property name with the “this” reserved word and the dot. I am referring here to the properties that belong to the prototypical object. The method, adds the two numbers assigned to the properties and returns the answer.

The object, coded as described is not usable. That is why it is called a prototypical object. Imagine that you want a usable object to be called, myObject and you want it to have the same properties and methods of the prototypical object; this is what you would do:

               myObject = new theObject();

Note the use of the “new” operator. After the “new” operator, you have the name of the constructor function, which is followed by (). The myObject object is usable. It has all the properties and methods of the prototypical object (theObject).

The last but one statement in the above code accesses the “add” method. This is the statement:

            result = myObject.add();

When you are calling a method you need the () brackets after the method name as shown here. However, when you are declaring a method you do not need the () brackets after the name of the method.

In the above code, the method returns the answer, which is held by the variable, result. The last statement in the code displays the result. You should try the above code (script).

So, to call a method, you begin with the usable object. This is followed by a dot and then the name of the method and the () brackets.

The Prototypical Object and Parameters
The construction function can have parameters. The following code illustrates this:

        <script type="text/javascript">
            function theObject(no1, no2)
                {
                    this.num1 = no1;
                    this.num2 = no2;
                    this.add  = function ()
                                    {
                                        answer = this.num1 + this.num2;
                                        return answer;
                                    }
                }

            myObject = new theObject(5, 8);

            result = myObject.add();
            alert(result);

        </script>

This script and the previous one do the same thing, but here the constructor function (prototypical object) has parameters. The arguments corresponding to the parameters become the values of the two properties. Most of the code should be self-explanatory. The line in the code that creates the usable object is:

            myObject = new theObject(5, 8);

As you can see, the arguments for the constructor function are passed at this stage. The assignments to the properties are done in the constructor function. From the above statement, the syntax to create a usable object from a constructor function is:

           objectName = constFnName(params)

where constFnName stands for Constructor Function Name and params stands for parameters.

Inheritance
You can create a child object from the usable object you have created. Such a child object is called an inherited object. The object inherited from is the parent object. You can still create another child object from the child object. You can carry on creating children object going down. In this way you would have a chain of descendant objects.

An inherited object inherits all the properties and methods of its parent object. In addition it can modify the inherited properties and methods and it can add new properties and methods.

The reserve word, “prototype” is used to create a child prototypical object from a (parent) prototypical object. Assume that you have two prototypical objects already existing in a code, you can make the second one the child object of the first as follows;

            secondObject.prototype = new firstObject;

In the above statement, after the second object name, you have a dot and then the reserved word, “prototype”. Next you have the assignment operator, then the name of the first object. The following code illustrates inheritance:

        <script type="text/javascript">
            function theObject()
                {
                    this.num1 = 5;
                    this.num2 = 8;
                    this.add  = function ()
                                    {
                                        answer = this.num1 + this.num2;
                                        return answer;
                                    }
                }

            function childObject()
                {
                    this.multiply = function ()
                                      {
                                          answer = this.num1 * this.num2;
                                          return answer;
                                      }
                }

            childObject.prototype = new theObject;

            myObject = new theObject();
            myChildObj = new childObject();

            result1 = myChildObj.num1;
            alert(result1);
            result2 = myChildObj.multiply();
            alert(result2);

        </script>

There are two prototypical objects in the code (script). The first one is called, theObject. The second one is called, childObject. The content of the first object is the same as what we have for the object in the previous code. The second one has one method that would multiply the values of properties of the first one, on condition that the second one becomes a child prototypical object of the first one. After the second prototypical object in the above code, you have the statement that makes the second prototypical object a child prototypical object of the first. The first object can be called the parent Prototypical object and the second one can be called the second prototypical object.

In the above code, the child prototypical object comes with a new (multiply()) method; the child prototypical object inherits all the properties and methods of the parent prototypical object. The child prototypical object can be defined in such a way that it modifies the parent prototypical object properties and methods.

Prototypical objects are not usable. The next two statements in the code create two usable objects from the parent and child prototypical objects.

The last four statements in the code demonstrate that the properties (and method) are indeed inherited and the child object acquired the a new (multiply()) method. Read through the code and try it.

Accessing Object Properties and Methods
You access a property in order to read or change its value. The syntax to access a JavaScript object property (outside the object code), is simply

                objectName.propertyName

There is a dot in between the object name and property name.

Generally you access a method to execute it: we say you call the method. The syntax for calling a JavaScript object method is

                objectName.methodName(args);

There is a dot in between the object name and method name. Some methods take arguments. If no arguments are involved, then you do not put anything in the () brackets; however, the brackets must be present when calling the method. Note: After the method name in the object code, the () brackets should not be present.

Adding Properties and Methods to an Object
All I will give you here is just the syntax. The syntax to add a new property to an object is,

            objectName.newPropName = value;

If the value is a string, it has to be in quotes. The syntax to add a new method to an object is,

           objectName.newMethodName = function (params)
                                                                 {
                                                                             method statements
                                                                 }


That is it: Creating JavaScript Objects by Constructor Function. I hope you appreciated it.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message