Broad Network


Creating ECMAScript Object from the Global Object

Custom Object in ECMAScript - Part 1

Foreword: In this part of the series, I explain how to create an object directly from the ECMAScript Global Object.

By: Chrysanthus Date Published: 21 Sep 2014

Introduction

This is part 1 of my series, Custom Object in ECMAScript. In this part of the series, I explain how to create an object directly from the ECMAScript Global Object. ECMAScript has one main object called, the Global Object. All objects come from the global Object. The global object is already created in your browser; you the programmer do not see the code. The global object code is executed before your own ECMAScript code is executed. So, the global object and its properties are available to your code.

A custom object is an object that you, the programmer produce (write). Any object you write, no matter the way in which you write it, comes from the global object.

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

Pre-Knowledge
The learning of any computer language builds up. You have to learn something first, and then use that to learn some other thing at a higher level. So, you should have cowered the following series before reaching here:

- ECMAScript Basics
- ECMAScript Operators
- Expressions and Statements in ECMAScript

The links to these free series are given below:

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

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

        <script type="text/ECMAScript">

         var num1 = 5;
         var num2 = 8;
         function add ()
                 {
                 answer = num1 + num2;
                 return answer;
                 }

         var result = add();
         alert(result);

        </script>

</body>
</html>

The extra HTML code is to produce a web page. As you can see in the code of interest, there are two variables (identifiers). The function adds the values of the two variables, and returns the answer. Down in the code, the function is called, and the return value is assigned to a new variable, result. The last statement alerts (displays) 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 in the code, the rest of the variables and the functions will not be very useful; also, 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, object. Many modern computer languages have each, its own syntax for creating an object. In this tutorial, I show you the most obvious way of creating an object in ECMAScript.

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 a 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; as illustrated below:

Ways of Creating an Object
You create any object from the global object. The global object has a property called, the constructor. This is an object in itself; it is also a function. It is the constructor that will create your custom object for you. In simple terms, the syntax for the constructor is:

    Object ()

Remember that ECMAScript is case sensitive, and so do not use object()  instead of Object().

You create your custom object using either one of the following statements:

    objectidentifier = Object();

or

    objectidentifier = new Object();

The second statement uses the new operator. The first statement is said to call the constructor as a function. The second statement is said to call the constructor as part of a new expression; that is, it is called in an expression that has the new operator. For the rest of this tutorial, the constructor will be called as part of a new expression. The result of using either approach is the same.

Creating your Object
When you create an object, you make it custom, by adding your own properties and methods to the object. The object constructor is an expression, “Object()” that when preceded by the word, “new”, an object is returned. You assign the returned object to a variable (identifier). As you add properties and/or methods (see below) to this returned object, you end up with your own custom object. The following code is a substitute for the above code, but with object features. The explanation is given after the code.

    <script type="text/ECMAScript">

        myObject = new Object();

        myObject.num1 = 5;
        myObject.num2 = 8;
        myObject.add = function ()
                            {
                                answer = myObject.num1 + myObject.num2;
                                return answer;
                            }

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

    </script>

Before we continue, note that only the last line of this code and the last line of the one above are exactly the same. Let us look at the present code. The first line creates your object. “Object()” is the object constructor. The word, “new” that precedes it is an example of what is called ECMAScript Operator. Whenever you want to create an object using the approach of this tutorial, use this “new” operator. After typing it, type space and then “Object()”. Remember that ECMAScript is case sensitive, so begin the constructor with uppercase O and not lowercase o. The right operand (new Object()) of the assignment operator, returns a new object that is assigned to the variable, myObject. The name (identifier), myObject is what you choose; you can choose any name you wish.

At this point the object has no properties and methods. The variables of the previous code are to become properties and the functions are to become methods. The syntax to declare a property is:

            objectName.propertyName

You begin with the object name, which in our case is, myObject. This is followed by a dot and then the property name, which in the second line of the above code is, num1. You can assign to a property, a value (5) as this second line shows. Whenever you assign a value, whatever property value that was there, is replaced. The third line in the code is for the second object property with name, num2 and value, 8. This property is in the place of the second variable we had in the first code.

The function in the first code becomes a method in the second code. You declare a method with the following syntax:

           objectName.methodName

In the second code, the object name is, myObject and the method name (identifier) is, add. You can give whatever method name you want; however, the name you give should be related in spelling to the purpose of the method. Next, you have the definition of the function, which is assigned to this property. After the “=” character, you have the reserved word, “function” in lowercase.  This is followed by () and then {}. Inside {}, you have the statements for the method. You do not have the name of the method after the reserved word, function; you have the name as part of the method declaration expression after the dot.

Let us look at the statements inside the method (function) definition of the above code. There are two statements. The first one is

                      answer = myObject.num1 + myObject.num2;

In the statement the first thing you have is the variable, answer. After the assignment operator, you have the expression, myObject.num1. This expression returns the value of the first property to that position. Next you have the plus sign and the expression, myObject.num2. This second expression returns the value of the second property to that position. Note that in the function definition, each of the property names is preceded by the object name. The values of the two properties are added in the statement in the right operand of the assignment operator and assigned to the variable, answer. The second statement in the method, returns the value of answer. So when this method is called, it would do the addition and returns the answer.

The above code has two properties for the objects and one method, corresponding to the two variables and one function in the first code.

The last but one statement in the above code calls the method of the object. You call a method of an object with the following syntax.

           objectName.methodName()

In our case, the object name is myObject and the method name is, add. Note that the method call name is followed by (). The parentheses can have arguments. However, in the definition of a method, the method name is not followed by (). In the definition, you can place parameters in the () after the reserved word, “function”.

The last but one statement in the above code, calls the method and assigns the return value to the new variable, result. The last statement displays the result.

Method and Arguments
A method can take arguments. In the method definition you place the parameters for the corresponding arguments in the parentheses after the reserved word, function. The following code is a modified form of the above. The method takes an argument and the value of it is used to multiply the sum. Read and try it:

    <script type="text/ECMAScript">

        myObject = new Object();

        myObject.num1 = 5;
        myObject.num2 = 8;
        myObject.addMulti = function (mult)
                            {
                                answer0 = myObject.num1 + myObject.num2;
                                answer1 = answer0 * mult;
                                return answer1;
                            }

     result = myObject.addMulti(2);
     alert(result);

    </script>

The result should be 26.

Accessing Object Properties and Methods
You access a property in order to read or change its value. The syntax to access an ECMAScript 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 an ECMAScript 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 property), the () brackets should not be present; the second code above illustrates this.

Adding Properties and Methods to an Object
All I will give you here is just the syntax. In the above example the object was first created before the properties and method added. 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
                                                             }

Function as Object
A function is a special kind of object in ECMAScript.

Summary
To create an object, use the following syntax:

          objectName = new Object();

or

          objectName = Object();

With objectName, you can add properties and methods (do not forget to use the dot). The second syntax here is not used in this series.

Well, let us stop here for this part of the series. We continue in the next part.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions and Statements in ECMAScript
Custom Object in ECMAScript
ECMAScript Global Object
The ECMAScript Array
The ECMAScript String Object
ECMAScript Regular Expressions
ECMAScript Date Object
ECMAScript Error Basics
Advanced Course
Number Objects in ECMAScript
Inheritance in ECMAScript
Advanced ECMAScript Regular Expressions
Mastering the ECMAScript (JavaScript) eval Function
More 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