JavaScript John Mitchell CS 242 Reading: links on last slide Homework 1: Sept 24 - Oct 1 Autumn 2008.

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

the javascript language BY SA.
Sue Wills July Objects The JavaScript language is completely centered around objects, and because of this, it is known as an Object Oriented Programming.
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Java Script Session1 INTRODUCTION.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
XP 1 JavaScript Source from multiple external sources from the Internet over the years Please PM me to claim credit if needed Known Arthur: John Mitchell.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
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.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
Slide 1 Vitaly Shmatikov CS 345 Scope and Activation Records.
JavaScript John Mitchell Adapted by Mooly Sagiv Reading: links on last slide Homework 1: 18/3 – 17/4 Spring 2012.
Taking JavaScript Seriously IS NOT THE WORST IDEA.
INF 212 ANALYSIS OF PROG. LANGS JAVASCRIPT Instructors: Crista Lopes Copyright © Instructors.
Programming Languages and Paradigms Object-Oriented Programming.
JavaScript JavaScript is a scripting language that is most commonly used to add client- side programming to a web page. Some of the things it is used for.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Slide 1 Vitaly Shmatikov CS 345 Introduction to JavaScript.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
JavaScript II ECT 270 Robin Burke. Outline JavaScript review Processing Syntax Events and event handling Form validation.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
SE-2840 Dr. Mark L. Hornick 1 Modifying webpage behavior using client-side scripting Javascript.
Introduction to JavaScript Gordon Tian
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Advanced topic - variable.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Slide 1 Introduction to JavaScript. slide 2 Common Uses of JavaScript uForm validation uPage embellishments and special effects uNavigation.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript, Fourth Edition
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
JavaScript Functions A function is a block of code that can be reused. It is similar to a method in Java. It consists of a function name, an argument.
1) PHP – Personal Home Page Scripting Language 2) JavaScript.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
JavaScript II ECT 270 Robin Burke. Outline Functions Events and event handling Form validation.
Java Script. introduction Today’s web sites need to go much beyond HTML. browsing through a web site, to actually interact with the web site. The web.
CGS 3066: Web Programming and Design Spring 2016 Programming in JavaScript.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript Tutorial First lecture 19/2/2016. Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a part.
Javascript Prof. Wenwen Li School of Geographical Sciences and Urban Planning 5644 Coor Hall
JavaScript John Mitchell Stanford University Revised by
CNIT 133 Interactive Web Pags – JavaScript and AJAX
Davide Morelli Giuseppe Attardi Dipartimento di Informatica
Client/Server Computing and Web Technologies
JavaScript and Ajax (Expression and Operators)
JavaScript an introduction.
DHTML Javascript Internet Technology.
DHTML Javascript Internet Technology.
T. Jumana Abu Shmais – AOU - Riyadh
CS5220 Advanced Topics in Web Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

JavaScript John Mitchell CS 242 Reading: links on last slide Homework 1: Sept 24 - Oct 1 Autumn 2008

Why talk about JavaScript? uVery widely used, and growing Web pages, AJAX, Web 2.0 Increasing number of web-related applications uSome interesting and unusual features First-class functions - interesting Objects without classes - slightly unusual Powerful modification capabilities - very unusual –Add new method to object, redefine prototype, access caller … uMany security, correctness issues Not statically typed – type of variable may change … Difficult to predict program properties in advance

JavaScript History uDeveloped by Brendan Eich at Netscape Scripting language for Navigator 2 uLater standardized for browser compatibility ECMAScript Edition 3 (aka JavaScript 1.5) uRelated to Java in name only Name was part of a marketing deal uVarious implementations available Spidermonkey interactive shell interface Rhino:

Motivation for JavaScript uNetscape, 1995 Netscape > 90% browser market share Opportunity to do “HTML scripting language” Brendan Eich I hacked the JS prototype in ~1 week in May And it showed! Mistakes were frozen early Rest of year spent embedding in browser uCommon uses of JavaScript include: Form validation Page embellishments and special effects Dynamic content manipulation Emerging Web 2.0: client functionality implemented at client - ICFP talk, 2006

Example 1: simple calculation … var num1, num2, sum num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) alert("Sum = " + sum) …

Example 2: browser events function whichButton(event) { if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") }} … … Mouse event causes page-defined function to be called Other events: onLoad, onMouseMove, onKeyPress, onUnLoad

Example 3: page manipulation uSome possibilities createElement(elementName) createTextNode(text) appendChild(newChild) removeChild(node) uExample: Add a new list item: var list = document.getElementById(‘list1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext) This example uses the browser Document Object Model (DOM). For now, we will focus on JavaScript as a language, not its use in the browser.

Design goals u Brendan Eich’s 2006 ICFP talk Make it easy to copy/paste snippets of code Tolerate “minor” errors (missing semicolons) Simplified onclick, onmousedown, etc., event handling, inspired by HyperCard Pick a few hard-working, powerful primitives –First class functions for procedural abstraction –Objects everywhere, prototype-based Leave all else out!

Language basics uJavaScript is case sensitive HTML is not case sensitive; onClick, ONCLICK, … are HTML uStatements terminated by returns or semi-colons (;) x = x+1; same as x = x+1 Semi-colons can be a good idea, to reduce errors u“Blocks” Group statements using { … } Not a separate scope, unlike other languages (see later slide) uVariables Define a variable using the var statement Define implicitly by its first use, which must be an assignment –Implicit definition has global scope, even if it occurs in nested scope?

Useful implementation uSpidermonkey command-line interpreter Read-eval-print loop –Enter declaration or statement –Interpreter executes –Displays value –Returns to input state Example class web page has link to this implementation

JavaScript blocks uUse { } for grouping; not a separate scope js> var x=3; js> x 3 js> {var x=4; x} 4 js> x 4 uNot blocks in the sense of other languages Only function calls and the with statement cause a change of scope

JavaScript primitive datatypes uBoolean Two values: true and false uNumber 64-bit floating point, similar to Java double and Double No integer type Special values NaN (not a number) and Infinity uString Sequence of zero or more Unicode characters No separate character type (just strings of length 1) Literal strings using ' or " characters (must match) uSpecial values null and undefined typeof(null) = object; typeof(undefined)=undefined

Objects uAn object is a collection of named properties Simple view: hash table or associative array Can define by set of name:value pairs –objBob = {name: “Bob", grade: 'A', level: 3}; New members can be added at any time –objBob.fullname = 'Robert'; Can have methods, can refer to this uArrays, functions regarded as objects A property of an object may be a function (=method) A function defines an object with method called “( )” function max(x,y) { if (x>y) return x; else return y;}; max.description = “return the maximum of two arguments”;

More about functions uDeclarations can appear in function body Local variables, “inner” functions uParameter passing Basic types passed by value, objects by reference uCall can supply any number of arguments functionname.length : # of arguments in definition functionname.arguments.length : # args in call u“Anonymous” functions (expressions for functions) (function (x,y) {return x+y}) (2,3); uClosures and Curried functions function CurAdd(x){ return function(y){return x+y} }; More explanation on next slide

Function Examples uAnonymous functions make great callbacks setTimeout(function() { alert("done"); }, 10000) uCurried function function CurriedAdd(x){ return function(y){ return x+y} }; g = CurriedAdd(2); g(3) uVariable number of arguments function sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } sumAll(3,5,3,5,3,2,6)

Use of anonymous functions uAnonymous functions very useful for callbacks setTimeout(function() { alert("done"); }, 10000) // putting alert("done") in function delays evaluation until call uSimulate blocks by function definition and call var u = { a:1, b:2 } var v = { a:3, b:4 } (function (x,y) { var tempA = x.a; var tempB =x.b; //local variables x.a=y.a; x.b=y.b; y.a=tempA; y.b=tempB }) (u,v) // This works because objects are passed by reference

Detour: lambda calculus uExpressions x + y x + 2*y + z uFunctions x. (x+y) z. (x + 2*y + z) uApplication ( x. (x+y)) (3) = 3 + y ( z. (x + 2*y + z))(5) = x + 2*y + 5

Higher-Order Functions uGiven function f, return function f  f f. x. f (f x) uHow does this work? ( f. x. f (f x)) ( y. y+1) = x. ( y. y+1) (( y. y+1) x) = x. ( y. y+1) (x+1) = x. (x+1)+1 In pure lambda calculus, ame result if step 2 is altered.

Same procedure, Lisp syntax uGiven function f, return function f  f (lambda (f) (lambda (x) (f (f x)))) uHow does this work? ((lambda (f) (lambda (x) (f (f x)))) (lambda (y) (+ y 1)) = (lambda (x) ((lambda (y) (+ y 1)) ((lambda (y) (+ y 1)) x)))) = (lambda (x) ((lambda (y) (+ y 1)) (+ x 1)))) = (lambda (x) (+ (+ x 1) 1))

Same procedure, JavaScript syntax uGiven function f, return function f  f function (f) { return function (x) { return f(f(x)); }; } uHow does this work? (function (f) { return function (x) { return f(f(x)); }; ) (function (y) { return y +1; }) function (x) { return (function (y) { return y +1; }) ((function (y) { return y + 1; }) (x)); } function (x) { return (function (y) { return y +1; }) (x + 1); } function (x) { return ((x + 1) + 1); }

Basic object features uUse a function to construct an object function car(make, model, year) { this.make = make; this.model = model; this.year = year; } uObjects have prototypes, can be changed var c = new car(“Ford”,”Taurus”,1988); car.prototype.print = function () { return this.year + “ “ + this.make + “ “ + this.model;} c.print();

JavaScript functions and this var x = 5; var y = 5; function f() {return this.x + y;} var o1 = {x : 10} var o2 = {x : 20} o1.g = f; o2.g = f; o1.g() 15 o2.g() 25 Both o1.g and o2.g refer to the same function object Why are the results for o1.g() and o2.g() different ?

More about this u Property of the activation object for fctn call In most cases, this points to the object which has the function as a property (or method). Example : var o = {x : 10, f : function(){return this.x}} o.f(); 10 this is resolved dynamically when the method is executed

Special treatment for nested methods var o = { x: 10 f : function() { function g(){ return this.x } ; return g(); } }; o.f() Function g gets the global object as its this property !

Language features in CS242 uStack memory management Parameters, local variables in activation records uGarbage collection Automatic reclamation of inaccessible memory uClosures Function together with environment (global variables) uExceptions Jump to previously declared location, passing values uObject features Dynamic lookup, Encapsulation, Subtyping, Inheritance uConcurrency Do more than one task at a time (JavaScript is single-threaded)

Stack memory management uLocal variables in activation record of function function f(x) { var y = 3; function g(z) { return y+z;}; return g(x); } var x= 1; var y =2; f(x) + y;

Garbage collection uAutomatic reclamation of unused memory Navigator 2: per page memory management –Reclaim memory when browser changes page Navigator 3: reference counting –Each memory region has associated count –Count modified when pointers are changed –Reclaim memory when count reaches zero Navigator 4: mark-and-sweep, or equivalent –Garbage collector marks reachable memory –Sweep and reclaim unreachable memory Reference Discuss garbage collection in connection with Lisp

Closures uReturn a function from function call function f(x) { var y = x; return function (z){y += z; return y;} } var h = f(5); h(3); uCan use this idea to define objects with “private” fields Description of technique – – king_with_Closures But there are subtleties (look for __parent__)

Exceptions uThrow an expression of any type throw "Error2"; throw 42; throw {toString: function() { return "I'm an object!"; } }; uCatch try { } catch (e if e == “FirstException") { // do something } catch (e if e == “SecondException") { // do something else } catch (e){ // executed if no match above } Reference: Core_JavaScript_1.5_Guide :Exception_Handling_Statements

Object features uDynamic lookup Method depends on run-time value of object uEncapsulation Object contains private data, public operations uSubtyping Object of one type can be used in place of another uInheritance Use implementation of one kind of object to implement another kind of object

Concurrency uJavaScript itself is single-threaded How can we tell if a language provides concurrency? uAJAX provides a form of concurrency Create XMLHttpRequest object, set callback function Call request method, which continues asynchronously Reply from remote site executes callback function –Event waits in event queue… Closures important for proper execution of callbacks uAnother form of concurrency use SetTimeout to do cooperative multi-tasking –Maybe we will explore this in homework …

JavaScript eval uEvaluate string as code The eval function evaluates a string of JavaScript code, in scope of the calling code uExamples var code = "var a = 1"; eval(code); // a is now '1‘ var obj = new Object(); obj.eval(code); // obj.a is now 1 uMost common use Efficiently deserialize a large, complicated JavaScript data structures received over network via XMLHttpRequest uWhat does it cost to have eval in the language? Can you do this in C? What would it take to implement?

Unusual features of JavaScript uSome built-in functions Eval, Run-time type checking functions, … uRegular expressions Useful support of pattern matching uAdd, delete methods of an object dynamically Seen examples adding methods. Do you like this? Disadvantages? myobj.a = 5; myobj.b = 12; delete myobj.a; uRedefine native functions and objects (incl undefined) uIterate over methods of an object for (variable in object) { statements } uWith statement (“considered harmful” – why??) with (object) { statements }

References uBrendan Eich, slides from ICFP conference talk uTutorial (still there?) uJavaScript 1.5 Guide _1.5_Guide uDouglas Crockford site JavaScript/