Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

Similar documents
Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript

CSC Web Programming. Introduction to JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

Client-Side Web Technologies. JavaScript Part I

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Such JavaScript Very Wow

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

JavaScript I VP R 1. Copyright 2006 Haim Levkowitz. Outline

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

CHAPTER 6 JAVASCRIPT PART 1

CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

Javascript. Many examples from Kyle Simpson: Scope and Closures

JavaScript: Introduction, Types

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

CISC 1600 Lecture 2.4 Introduction to JavaScript

a Why JavaScript? jonkv interactivity on the web CGI JavaScript Java Applets Netscape LiveScript JavaScript 1: Example

Chapter 4 Basics of JavaScript

CGS 3066: Spring 2015 JavaScript Reference

4.1 Overview of JavaScript

JavaScript: The Basics

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

CERTIFICATE IN WEB PROGRAMMING

JavaScript Specialist v2.0 Exam 1D0-735

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

JavaScript: More Syntax and Using Events

Introduction to Web Tech and Programming

COMS 469: Interactive Media II

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

INF5750. Introduction to JavaScript and Node.js

JavaScript Functions, Objects and Array

The JavaScript Language

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Working with JavaScript

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

PERL Scripting - Course Contents

Software. Programming Languages. Types of Software. Types of Languages. Types of Programming. Software does something

PIC 40A. Midterm 1 Review

Documents and computation. Introduction to JavaScript. JavaScript vs. Java Applet. Myths. JavaScript. Standard

dhtml2010.pdf February 25,

JavaScript: Introductionto Scripting

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Session 6. JavaScript Part 1. Reading

Web Site Development with HTML/JavaScrip

JAVASCRIPT. Ajax Technology in Web Programming. Sergio Luján Mora. DLSI - Universidad de Alicante 1. Basic syntax and features

Lecture 8 (7.5?): Javascript

Javascript. Daniel Zappala. CS 360 Internet Programming Brigham Young University

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

1. Cascading Style Sheet and JavaScript

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

Session 16. JavaScript Part 1. Reading

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

New Media Production Lecture 7 Javascript

Tutorial 10: Programming with JavaScript

University Convocation IT 3203 Introduction to Web Development Creating Objects Accessing Property Values

JavaScript s role on the Web

Fundamentals of Website Development

UNIT-III THE BASICS OF JAVASCRIPT

Full file at

Govt. of Karnataka, Department of Technical Education Diploma in Computer Science & Engineering. Fifth Semester. Subject: Web Programming

3 The Building Blocks: Data Types, Literals, and Variables

Hands-On Perl Scripting and CGI Programming

isnan function returns true if the argument is not a number otherwise it is false.

Chapter 7 Applets. Answers

JavaScript: Sort of a Big Deal,

Ruby: Introduction, Basics

COMS 469: Interactive Media II

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

Pace University. Fundamental Concepts of CS121 1

CS312: Programming Languages. Lecture 21: JavaScript

Why Discuss JavaScript? CS312: Programming Languages. Lecture 21: JavaScript. JavaScript Target. What s a Scripting Language?

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

Web Programming Step by Step

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Chapter 3 Data Types and Variables

GNU ccscript Scripting Guide IV

JScript Reference. Contents

Web Programming/Scripting: JavaScript

CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM

JavaScript: More Syntax

JavaScript Basics. Mendel Rosenblum. CS142 Lecture Notes - JavaScript Basics

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

More on JavaScript Functions

(Refer Slide Time: 01:40)

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

JavaScript Basics. The Big Picture

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

Shankersinh Vaghela Bapu Institue of Technology

DC71 INTERNET APPLICATIONS JUNE 2013

Web Development & Design Foundations with HTML5

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

Transcription:

Lecture 3: The Basics of JavaScript Wendy Liu CSC309F Fall 2007 Background Origin and facts 1 2 Needs for Programming Capability XHTML and CSS allows the browser to passively display static content How to provide/request for more services? How to provide dynamic information? How to handle demands from the client? How to respond instantly to user actions? Demand for programming capability Origin of JavaScript Created to provide programming capability at both the server and the client ends of a Web connection Originally known as LiveScript Official name - ECMAScript http://www.ecma-international.org/publications/standards/ecma-262.htm Three parts Core Operators, expressions, statements, and subprograms Client-side A collection of objects that support control of a browser and interaction with users XHTML-embedded scripts An XHTML document may include any number of embedded scripts Server-side A collection of objects in support of a Web server (e.g. communicating with DBMS) 3 4 Using Client-side JavaScript Embedded in XHTML documents (physically or logically) Interpreted by the browser Objects representing windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output Transfer load from server to client Cannot replace all server-side computing, e.g. file operations, DB access, and networking Easy to implement event-driven computation Interaction with users Triggering computation on events Focus change, page and image loading, unloading, error and abort, selection, form submission, and mouse actions Generate new content dynamically Access and modify CSS properties and content of any XHTML element (through the Document Object Model (DOM)) Facts of JavaScript Variables need not be declared and are dynamically typed Objects are dynamic Number of data members and methods of an object may change during execution Prototype-based inheritance An object-based web scripting language Basic language and host facilities are provided by objects Not an object-oriented programming language Does not have classes Its objects serve both as objects and models of objects Does not support OO development paradigm Syntax is similar to Java Expression, assignment statements, and control statements 5 6 1

Scripting Language A scripting language is a programming language that is used to manipulate, customise, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language. A scripting language is intended for use by both professional and nonprofessional programmers. To accommodate nonprofessional programmers, some aspects of the language may be somewhat less strict. -- ECMA-262 Getting Started with JavaScript Basics 7 8 Embedding in XHTML Directly <script type="text/javascript"> <!-- JavaScript code // --> </script> Indirectly <script type="text/javascript" src="test.js"></script> Location Within <head> Within <body> Evaluation Evaluation and Execution As document is parsed, in order Execution Statements outside functions When encountered Statements inside a function When the function is called Event handler <body onload= helloworld() > 9 10 <head> <title> Greetings </title> <script type="text/javascript"> <!-- document.write("top"); function f(){ document.write( f: "+x); // --> </script> </head> Example 1 <body> <p> A simple example: <br/> <script type="text/javascript"> <!-- var x=1; f(); document.write("; Bot: "+x); // --> </script> </p> </body> Syntactic Characteristics Identifiers or names Must begin with a letter, _, or $ No length limitation Case sensitive Comment // Comment out the rest of the line /* comment out within the enclosure*/ Semicolon (;) End of statement Interpreter may insert one if absent (be careful) return becomes return; x; x; 11 12 2

Number Primitive Types e.g. 72 7.2.72 72. 7e2.7E2 7.2e-2 String a string also string (null strings) Boolean true false Undefined undefined Null null The first three types also have predefined objects Control if then else switch Looping Control and Looping for( init ; control ; inc) while ( control ) do while for.. in for (property in object) { 13 14 Functions function fname ([arg1] [,, argn]) { [return [value];] Parameters Primitive types (string, number, boolean) are passed by value Object types are passed by reference Determining the number of actual parameters arguments.length Functions are objects Example 2 function f1(mylist) { var newlist = new Array(1, 2, 3); mylist[3] = 4; mylist = newlist; var list = new Array(6, 7, 8); f1(list); 15 16 Variables Dynamically typed Variables are not typed, values are Type is determined by the interpreter on each instance Declaration Explicit (recommended) var i = 12, count; // value is undefined Implicit msg = hello ; Scope Global Declared outside functions Any variable implicitly defined Local Explicit declarations inside functions var x=1; function f(){ var y = 2; function g(){ var z = 3; Scope Chain x: 1 y: 2 z: 3 global object call object of scope f() call object of scope g() 17 18 3

Example 3 var x=1; document.write("top: "+x); function f(){ document.write("; top f(): "+x); var x = 2, y=0; document.write("; mid f(): "+x); x=y; document.write("; before g(): "+x); function g(){ var z = 3; x=z+y; document.write("; in g(): "+x); g(); document.write("; after g(): "+x); f(); document.write("; Bottom: "+x); Top: 1; top f(): undefined; mid f(): 2; before g(): 0; in g(): 3; after g(): 3; Bottom: 1 Implicit conversion Coercion Examples Type Conversions August + 20 string August 20 string 7 * 3 number (21) 7 * Aug NaN As a number null is 0 undefined is NaN As Boolean 0, NaN, undefined, null, empty string is false all other numbers or strings are true true == 1, false == 0 Explicit conversion var num = 6, s = num.tostring(), s2 = num.tostring(2); var b = String( 2007 ), n = Number(b), m = b 0; 19 20 JavaScript Objects Objects are collections of properties Like associative arrays (or maps) var point = new Object(); point.x = 2; Each property can be Data property Primitive value Reference to other object Function or method (property) Objects are indirectly accessed by variables Like references The root object is Object Object definition is determined at run time. Properties can be added or modified anytime Object Constructors Special methods for creating and initializing properties of the new objects function Rectangle_area() { return this.width * this.height; function Rectangle(w,h) { this.width = w; this.height = h; this.area = Rectangle_area; var rec = new Rectangle(2,4); var a = rec.area(), b = rec[ area ](); rec.newfunction = newpredecleredfunc; 21 22 Alternatively function Rectangle(w,h) { this.width = w; this.height = h; this.area = function () { return this.width * this.height; var rec = new Rectangle(2,4); A Subtle Point Inheritance rec.area(); rec[ area ](); Rec.newFunction = newpredecleredfunc; 23 24 4

Prototype-based Inheritance Prototype Example function car(themake, themodel){ this.prototype = constructor.prototype; this.make = themake; this.model = themodel; var greencar = new car("toyota", "camry"); var redcar = new car("honda", "accord"); redcar.prototype.speed = function (i){ return i*2; document.write(greencar.make + " + greencar.model + "'s speed is " + greencar.prototype.speed(3)+ "<br/>"); document.write(redcar.make + " " + redcar.model + "'s speed is " + redcar.speed(5)); 25 26 Predefined Objects More Sophisticated JavaScript Useful Objects Native objects ( Built-in objects) Object, Function, Array, String, Boolean, Number, Math, Date, RegExp, Error Primitive types are automatically coerced into Objects Host objects Navigator Window Document 27 28 Dynamic length Array Elements may be primitive values or references Index starts from 0 Modify.length to change array size All array elements are allocated dynamically var a = new Array(); // empty array var b = new Array( dog, 3, 8.4); var c = new Array(10); // array of size 10 var d = [2, 5, a, b ]; c[15] = hello ; // implicit extension length join() reverse() sort() concat() Array Properties and Methods slice() splice() push() / pop() shift() / unshift() tostring() 29 30 5

Represents the browser Properties appname Browser name appversion Browser version platforms Client OS cookieenabled cpuclass browserlanguage online navigator Object document Object Container for all HTML-related objects Content nested inside <html> tag Methods open() Opens a stream to collect the output from any document.write() write() Appends text to document Properties URL 31 32 window Object Browser window itself Methods open(url,name,[options]) open a new window close() alert() popup alert prompt() user input Properties document width, height toolbar, menubar, scrollbar, status, location resizable screenx, screeny Keyboard input Input and Output alert( Passwords must be at least 4 characters. ); var question = confirm( Do you want to submit? ); var name = prompt( What is your name?, ); Screen output document.write( Name: + name); 33 34 Pattern Matching Patterns are specified as regular expressions Based on Perl s regular expressions Two approaches String object search( pattern ) return start position of a match returns -1 if no match replace( pattern, value ) match( pattern ) split( pattern ) RegExp object Strings and Regular Expressions match(regexpobj) Verify input var phone = "416-4403467"; if (phone.match(/\d{3-\d{7/)) return true; replace(regexpobj, str) Replace part of a string var str = "One elephant and two zebras"; var matches = str.replace(/two/,"three"); 35 36 6

\w An alphanumeric \d A digit \s A white space. Anything other than newline [abcde] Any of a,b,c,d,e [a-e] Same as above String Object Approach [^a-e] Anything but a to e exp?, exp+, exp* 0 or 1, 1 or more, 0 or more symbolic quantifiers exp{x Exactly x repeats exp{x, y At least x repeats, but no more than y repeats expa expb expa or expb /exp/i Match either upper or lowercase in exp RegExp Object Approach RegExp object var animalsearch = /bear/; var animalsearch = new RegExp( bear ); Methods exec(str) return the match from str test(str) returns true if match if (animalsearch.test( The little bear )) { alert( I found a bear ); 37 38 JavaScript Security Language/API limitations No file/directory access defined in the language No raw network access, limited to Load URLs Send HTML form data to web servers, CGI scripts, e-mail addresses same origin policy Can only read properties of documents and windows from the same origin host, port, protocol Privacy restrictions Cannot read history Cannot hide/show menubar, status line, scrollbars Cannot close a window not opened by itself 39 7