Broad Network


Object Basics in ECMAScript 2015

ECMAScript Basics - Part 10

Object, Basics, ECMAScript, 2015,

Foreword: The aim of this tutorial is to quickly make you understand the meaning of Programming Objects (OOP) and how to create them in ECMAScript.

By: Chrysanthus Date Published: 12 May 2016

Introduction

This is part 10 of my series, ECMAScript Basics. The aim of this tutorial is to quickly make you understand the meaning of Programming Objects (OOP) and how to create them in ECMAScript.

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:

        <script type="text/ECMAScript">

         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 (identifiers). The function adds the values of the two variables, and returns the answer. Down in the same 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:

Object already created
The ECMAScript inventors are smart. They created an ECMAScript global Object and had it in the Browser. You the programmer do not see the global object but it is there for you to easily use to create your own objects. This object is like a parent object.

Creating your Object
To create your own object from the parent object mentioned above, you use what is called the Object Constructor. The object constructor is an expression that when preceded by the word, “new” the parent object mentioned above is returned. You assign the returned object to a variable. As you add properties and/or methods (see below) to this returned object, you end up with your own 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 a 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 no 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 current 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 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 and assign it to this declaration (to result in a method). 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 return the answer.

The current code has two properties and one method for the object; these correspond to the two variables and one function in the first code.

The last but one statement in the current 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 name in the call, is followed by (). The parentheses can have arguments. 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 current 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 can 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:

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

    <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>

</body>
</html>

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 definition code, the () brackets should not be present.

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; you can consult it for illustration. 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
                                                                 }

Summary
To create an object, use the following syntax:

         objectName = new Object();

With objectName, you add properties and methods.

Well, let us stop here and continue in the next part of the series.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message