1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

JS1-1 Introduction to JavaScript (JavaScript 2) Xingquan (Hill) Zhu
Session 8 JavaScript/Jscript: Objects Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
JavaScript, Third Edition
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Introduction to scripting
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Scripting Languages.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Week 9 PHP Cookies and Session Introduction to JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
JavaScript, Fourth Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Using Client-Side Scripts to Enhance Web Applications 1.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Lecture 9 The Basics of JavaScript Boriana Koleva Room: C54
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
M. Taimoor Khan Javascript Objects  Every data-type defined in Javascript is an object  It has a class definition for.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JS1-1 Introduction to JavaScript (JavaScript 1) Xingquan (Hill) Zhu
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
JavaScript and Ajax (JavaScript Functions) Week 5 Web site:
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript: A short introduction Joseph Lee Created by Joseph Lee.
Basic Objects. Math Object  Math.cos( x ), x in radians  Math.sqrt ( x )  Math.pow ( x, y )  Math.ceil( x )  etc.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Chapter VII: Arrays.
>> Introduction to JavaScript
Unit 2 Client-Side Programming: the JavaScript Language
Chapter 4 Client-Side Programming: the JavaScript Language
SEEM4570 Tutorial 05: JavaScript as OOP
Introduction to Scripting
JavaScript Syntax and Semantics
JavaScript: Functions.
JavaScript.
Chapter 3 Introduction to Classes, Objects Methods and Strings
WEB PROGRAMMING JavaScript.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript: Introduction to Scripting
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)

JavaScript Objects  Objects are collections of properties (equivalent to members of classes in Java)  Properties are either data properties or method properties  Data properties are either primitive values or references to other objects  Subprograms called through objects are called methods, subprograms not called through objects are called functions  The Object object is the ancestor (through prototype inheritance) of all objects in a JavaScript program Object has no data properties, but several method properties 2

JavaScript Objects  JS has built-in objects E.g. Math, Date  Browser creates objects These model the document (web page)  You can create your own objects But JS has no class Objects are built on-the-fly 3

 There are objects corresponding to the 3 data primitives Number, String, Boolean (note the upper case first letter)  These wrap a single value and provide some methods One method all three wrapper objects have is valueOf() - returns the corresponding primitive value of an object  Create an object with new: var doneObj = new Boolean(true); var numObj = new Number( ); 4 Built-in Objects

 Boolean has no useful methods of its own  Number has formatting methods toExponential(digitsAfterDP) - converts the value of the object into an exponential notation with the # requested digits after. var num = new Number(10000); document.write (num.toExponential(1)); writes into document 1.0e+4 toPrecision(numberOfDigits) - converts a number into a number with the specified number of digits toFixed(digitsAfterDP) - rounds the number to the specified number of decimal places 5 Built-in Objects

 String has many methods  Many are the same as for Java String object indexOf, charAt, substring, etc. (we discussed some of these)  Also has methods to create HTML strings var st = new String(“I’m big and bold!”); var st1 = st.bold(); var out = st1.big(); gives I’m big and bold!  See for a complete reference 6 Built-in Objects demoStringToHtml.htm l

 JS does many automatic conversions between primitives and objects  Previous example could be written: var st = “I’m big and bold!”; var out = st.big().bold();  In this case, the variable st is automatically converted to a String object to make the first method call and the resulting string is then converted to a String object to call bold( ) 7 Object Conversions

 Math Like Java Math No instance needed – all constants and methods referenced through the Math object Constants ○ Math.PI. Math.SQRT2, etc. Methods ○ Trig functions: Math.sin( ), etc. ○ Number manipulation: Math.floor( ), Math.min( ), Math.round() ○ Calculational: Math.pow( ), Math.exp( ), Math.random( ) - like Java: [0, 1) 8 Other Built-in Objects

 Date var dt = new Date( ); gives the current date  Date has getX and setX methods for X = FullYear, Month, Day, Hours, Minutes, Seconds and Milliseconds  Formatting methods return date as a string toString( ) toGMTString( ) – converts to a string according to Greenwich time. toLocaleString( ) 9 Other Built-in Objects date.html

 JS has arrays which look like Java arrays Standard variable names to reference Array objects Indexed with [ ]  JS arrays are objects! Can be created with new keyword var newAr = new Array(“one”, “two”, “three”, 4); var newAr = new Array(3); 1 st way creates and initializes array (> 1 argument) 2 nd way just sets size (1 int argument)  Can also be created with array literal var newAr = [“one”, 2, “three”]; Note the square brackets, not braces Note that values of different data types can be mixed 10 Arrays

 Array elements are accessed as in Java: var first = newAr[0];  Can be multi-dimensional as in Java .length property gives the current length = the highest subscript to which a value has been assigned + 1, or the initial size, whichever is larger Can be read or written  Arrays are not fixed in length By setting new array elements using an index beyond the current length, or by setting the length property to a larger value you extend the array (very much NOT like Java) By setting the length property to a smaller value you shrink the array Space is not reserved for each element, only those defined (assigned) var a = new Array(5); // all are undefined a[100] = 2; // has only 1 defined 11 Arrays

 Flexibility of arrays allows many methods; var list = [2, 4, 6, 8, 10] slice() – returns part of an array: list.slice(1,3) => array [4, 6] concat( ) – concatenates new elements to the end of the array; returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12] join( ) – creates a string from the array elements, separated by commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10” reverse( ) – reverses order of the array elements; affects calling array sort( ) – converts elements to strings, sorts them alphabetically (or you can specify another order as a function); affects calling array push( ), pop( ) – add/delete elements to the high end of array unshift( ), shift( ) – add/delete elements at the beginning of the array 12 Arrays

 Array with non-numeric indices  Also called a hash  Created as Object and filled using index value var myHash = new Object(); myHash[“me”] = “Instructor”; myHash[“you”] = “Student”; for (var i in myHash) alert (i + "-" + myHash[i]); 13 Associative Arrays demoArrays.html

 Several types of JS functions exist  We will focus on simple declarative functions Like Java methods  Defined with keyword function  Parameters follow in parentheses No parameter types required () required even if no parameters are declared  Body of function in brackets (=compound statement)  Function terminates at end } or with return statement  No return type is declared Function can return a value of any type or have no return value 14 Functions

 Example: function greet(hour, name) { if(hour < 12) document.write(“Good morning, “+name); else if(hour < 18) document.write(“Good afternoon, “+name); else if(hour < 24) document.write(“Good evening, “+name); else return false; } 15 Functions

 Note that the example function may or may not return a value. If no value is returned explicitly from function, the undefined value is return by default ○ Could test by: var result = greet(hour, name); if(result != undefined) document.write(“Wrong hour”); ○ Note: no quotes on undefined 16 Functions

 Functions used like Java methods Calculations Data checking Any process you do more than once or want to isolate Note: a function definition should precede calls to the function, to guarantee it is loaded before being called → usually placed in head section 17

 Formal parameters are local variables  All other local variables must be declared with var or else a global variable may be used  Data types of arguments are not checked – just converted as needed 18 Functions demoFunctionArgs.htm l

 JS uses pass-by-value parameter- passing method Primitives are passed by value  Changing the value in the function has no effect at the calling site Objects are passed by reference  Changing the object in the function changes the caller’s object 19 Functions

 Number of arguments passed to a function is not checked against the number of formal parameters in the called function Excess actual parameters are ignored (however, see below) Excess formal parameters are set to undefined ○ i.e. if you define function f(a, b, c) and call it by f(p, q) then c will be undefined when f executes However, a property array named arguments holds all of the actual params, whether or not there are more of them than there are formal params: for (var i=0; i<arguments.length; i++) document.write(arguments[i] + “ ”); 20

 The new expression is used to create an object: This includes a call to a constructor method The new operator creates a blank (empty) object, the constructor creates and initializes all properties of the object  Properties of an object (data and methods) are accessed using a dot notation: object.property; or the object[property] notation. 21 User-defined Objects, Creation & Modification

 Properties are not variables, they are just the names of values, so they are not declared An object may be thought of as a Map/Dictionary/Associative-Storage  The number of properties of an object may vary dynamically in JS; properties can be added/deleted from an object at any time during interpretation 22

 Create my_car and add some properties // Create an Object object with no properties var my_car = new Object(); // Create and initialize the make property my_car.make = "Ford"; // Create and initialize the model property my_car.model = "Contour SVT";  The delete operator can be used to delete a property from an object delete my_car.model 23 User-defined Objects, Dynamic Properties

 Syntax:for (identifier in object) statement or compound statement  The loop lets the identifier take on each property (name) in turn in the object  Printing the properties in my_car: for (var prop in my_car) document.write("Name: " + prop + "; Value: " + my_car[prop] + " ");  Result: Name: make; Value: Ford Name: model; Value: Contour SVT 24 The for-in Loop

 Functions are objects in JavaScript  Functions may, therefore, be assigned to variables and to object properties Object properties that have function values are methods of the object  Example: function fun() { document.write("This surely is fun! "); } ref_fun = fun; // Now, ref_fun refers to the fun object fun(); // A call to fun ref_fun(); // Also a call to fun 25 Functions are Objects

 Constructors are functions that create and initialize properties for new objects; have same name as object being created  A constructor uses the keyword this in the body to reference the object being initialized 26 Constructors demoConstructor.ht ml

Constructors  Object methods are properties that refer to / point to functions A function to be used as a method may use the keyword this to refer to the object for which it is acting  As in Java, the JavaScript user-defined objects can be quite powerful and quite complicated…  We won’t really need to use them for form verification… 27

Development of JavaScript  To run JavaScript code, you may need to change the browser’s security settings.  IE 7 prevents by default scripts on your local computer from running; Check the “Allow active content to run in files on MyComputer” box in Tools / Internet options / Advanced / Security  Firefox has JavaScript enabled by default 28

Errors in Scripts  JavaScript errors are detected by the browser  Different browsers report this differently Firefox uses a special console IEdbl click => 29