Friday, 1 May 2015

html tutorials session 15

Introduction

Consider a scenario where a Web page has been designed to greet the user with his/her name on the click of a button. A code can be used here to accomplish this task, but may result in the same output on repetitive execution. However, writing these statements each time for the same action is tedious, time consuming, and error prone.
To make the code more task-oriented and manageable, JavaScript allows to group statements before they are actually invoked. This can be achieved by using the concept of functions. A function is a reusable block of code that is executed on the occurrence of an event. The event can be a user action on the page or a call within the script.
Functions
A function is an independent reusable block of code that performs certain operations on variables and expressions to fulfill a task. A function might take parameters, which are variables or values on which it performs operations. After performing operations, a function might return the resultant value to display it in the browser. For example, a function named Add() might take two numbers on which the addition operation will be performed and will return the result of addition.
A JavaScript function is always created under the script element. JavaScript supports both user-defined and built-in functions.

Declaring and Defining Functions
JavaScript allows declaring a function using the function keyword. The keyword is followed by the name of the function and parameters enclosed within the parenthesis. If the function does not take any parameters, then it must be specified with the empty parenthesis.
Once the function is declared, you need to define the function by specifying the operations or instructions within the curly braces { and }. These curly braces indicate the start and end of the function block, which is collectively referred to as the body of the function.
There are certain conventions that must be followed for naming functions. They are as follows:
Can consist of letter, digits, and underscore
Can begin only with a letter or an underscore
Cannot be a JavaScript keyword
Cannot begin with a digit
Cannot contain spaces
The syntax to create a function in JavaScript is as follows:
Syntax:
function function_name(list of parameters)
{
// Body of the function
}
where,
function: Is a keyword used to declare a function.
function_name: Indicates the name of the function.
list of parameters: Is optional and specifies the parameters to be passed to the function separated by commas.
A function must be defined, before it can be invoked in the script. Also, there can be multiple functions defined within the script element.
 Concepts Session 15 Functions and Objects V 1.1 © zetutorials Limited 
15.2.2 Invoking Functions
A function need to be invoked or called to execute it in the browser. To invoke a function, specify the function name followed by parenthesis outside the function block.
A function can be defined and invoked even in an external JavaScript file. Also, a function can be called from another function in JavaScript. The function that invokes another function is called the calling function; whereas the function that is called is referred to as the called function.
Functions provide the benefit of code reusability by allowing the user to call a function multiple times.
Concepts Session 15 Functions and Objects V 1.1 © zetutorials Limited

15.2.3 Parameterized Functions
Parameterized functions refer to JavaScript functions that take parameters. These parameters hold values on which the function needs to perform operations. Parameterized functions can be created to accept values for performing operations. 402 of 590 Concepts Session 15 Functions and Objects V 1.1 © zetutorials Limited

As shown  the num1 and num2 parameters will hold the values of val1 and val2 arguments to perform the operations. The num1 and num2 parameters are only accessible within the function, whereas the val1 and val2 variables are accessible anywhere within the script element.
The parameters of a function are variables that are declared in the function declaration. Here, num1 and num2 are the parameters of the function. Similarly, arguments are the values passed to the function. Here, val1 and val2 are the arguments whose values are passed to the parameters, num1 and num2, while invoking the function.
Alternatively, one can use same variable names for arguments and parameters while creating and invoking functions. In either of the case, the variables will occupy different memory space.
15.2.4 Ways of Passing Arguments
There are two ways of passing arguments to a function namely, pass by value and pass by reference. The description about these is as follows:
Passing by value - Refers to passing variables as arguments to a function. In the pass by value method, the called function do not change the values of the parameters passed to it from the calling function.

<script>
var names =new Array(‘James’, ‘Kevin’, ‘Brad’);
function change_names(names)
{
names[0]= ‘Stuart’;
}
function display_names()
{
document.writeln(‘<H3> List of Student Names:</H3>’);
document.write(‘<UL>’);
for(vari=0; i<names.length; i++)
{
document.write(‘<LI>’ + names[i]+ ‘</LI>’);
}
document.write(‘</UL>’);
change_names(names);
document.write(‘<H3> List of Changed Students Names:</H3>’);
document.write(‘<UL>’);
for(vari=0; i<names.length; i++)
{
document.write(‘<LI>’ + names[i]+ ‘</LI>’);
}
document.write(‘</UL>’);
}
display_names(names);
</script>    
the code, the function change_names(names) takes the names array as parameter. It changes the value at the 0th position in the array. The function is further invoked in the display_names() function. The display_names() function displays the values from the array before and after the value is changed at the 0th position in the array.
return Statement
A function operates on its parameters that might lead to some output values. This output needs to be displayed to the user or it needs to be sent back to the calling function. JavaScript allows sending the result back to the calling function by using the return statement.
The return statement begins with return keyword followed by the variable or value, which needs to be returned to the calling function. The return statement can also be used to halt the execution of the function and to return the control to the calling function. This is required when a particular condition is false or when there are chances of unexpected results during the code execution.

<script>
function factorial(num)
{
if(num==0)
return 0;
else if(num==1)
return 1;
else
{
var result =num;
while(num>1)
{
result = result *(num-1);
num--;
}
return result;
}
}
var num=prompt(‘Enter number:’,’’);
var result = factorial(num);
alert(‘Factorial of ‘ +num+ ‘ is ‘ + result + ‘.’);
</script>    
The code defines a function named factorial() which takes the num variable as the parameter. The execution of the script starts from the prompt() function, which takes the number from the user and stores it in the num variable. Next, the factorial() function is invoked by passing the num argument. If the user enters the value as 0 or 1, the function returns the value as 0 or 1 respectively. For any other number, the function calculates the factorial and returns the output value by using the return statement. The output is stored in the result variable, which is displayed to the user.
Objects
Objects are entities with properties and methods and resemble to real life objects. Properties specify the characteristics or attributes of an object, while methods identify the behavior of an object. For example, consider a real life object namely, Car.
Built-in Objects - Are pre-defined objects which are already defined. Their properties and methods need to be called to fulfill a task. An example of a pre-defined object is the Array object.
Custom Objects - Are user-defined objects, which the developer explicitly creates in the script and defines their properties and methods. For example, to store the doctor details, such as name, age, hospital name, and so on, an object named doctor can be created
Creating Custom Objects
The Object object is the parent object from which all JavaScript objects are derived. The custom objects can be derived from this object by using the new keyword.
There are two main methods to create a custom object. In the first method, an object can be created by using the built-in Object object, which is also known as the direct method.
In the second method, an object can be created by defining a template and initializing it with the new keyword.
The syntax to create the object using these methods are as follows:
Direct Method
The syntax to create a custom object using the Object object is as follows:
Syntax:
var object_name = new Object();
where,
object_name: Is the name of the object.
new: Is the keyword that allocates memory to the custom object. This is known as instantiation of an object.
Object: Is the built-in JavaScript object that allows creating custom objects
Template Method
An object’s template refers to a structure that specifies the custom properties and methods of an object. There are two steps in creating an object by using this method. First, the object type is declared using a constructor function. Second, you specify the object of the declared object type by using the new keyword.
JavaScript allows creating a reusable template without having to redefine properties and methods repeatedly to fulfill a particular object’s requirements. This template is known as the constructor function.
A constructor function is a reusable block that specifies the type of object, its properties, and methods. It might or might not take any parameters. After creating the constructor function, you specify an object of the declared object type using the new keyword. The new keyword allocates memory for the object and invokes a constructor function.
The syntax to create a constructor function is as follows:
Syntax:
function object_type(list of parameters)
{
// Body specifying properties and methods
}
where,
object_type: Indicates the object type.
list of parameters: Is optional and specifies the parameters to be passed to a function separated by commas.
The syntax to create the object using the new keyword is as follows:
Syntax:
object_name = new object_type(optional list of arguments);
where,
object_name: Is the name of the object.
Code Snippet 3 shows the creation of objects using direct method and template method.

<script>
//create an object using direct method
var doctor_details=new Object();
//create an object using new keyword
studOne = new student_info (‘James’, ‘23’, ‘New Jersey’);
</script>    

In the code, doctor_details object is created using the Object object. After creating the object, properties and methods can be specified. Similarly, student_info object is created using new keyword. The values ‘James’, ‘23’, and ‘New Jersey’ are the properties of the student_info which are initialized by constructor function during creation.

Creating Properties for Custom Objects
Properties specify the characteristics of an object. They can be specified for objects created through Object or template method.
To create and access a property of an object created using Object object, specify the object name followed by a period and the property name.


script>
var student_details=new Object();
student_details.first_name= ‘John’;
student_details.last_name= ‘Fernando’;
student_details.age= ‘15’;
alert (‘Student\’s name: ‘ +student_details.first_name+ ‘ ‘ +
student_ details.last_name);
</script>    

The code specifies three properties of the student_details object namely, first_name, last_name, and age along with their values. The values of these properties are displayed in the browser using the write() method


<script>
// To define the object type
function employee_info(name, age, experience)
{
this.name = name;
this.age= age;
this.experience= experience;
}
// Creates an object using new keyword
empMary = new employee_info(‘Mary’, ‘34’, ‘5 years’);
alert (“Name: “+ empMary.name + ‘\n’ +”Age: “+empMary.age+ ‘\n’
+”Experience: “+empMary.experience);
</script>    

The code specifies three properties namely, name, age, and experience along with their values in the constructor function. The object named empMary is created, which passes the values as the arguments. This invokes the constructor function and initializes the properties to their values. The this keyword is a reference to the current object whose properties are being initialized. It is used in the constructor to resolve conflict between the property and the parameter, both of which have the same name. The this keyword marks the distinction between the two, while assigning the value to the properties of an object.

No comments:

Post a Comment