Unformatted text preview:

Introduction to JavaScriptWhat’s a Scripting Language?Why JavaScript?JavaScript HistoryMotivation for JavaScriptCommon Uses of JavaScriptExample 1: Add Two NumbersExample 2: Browser EventsExample 3: Page ManipulationDocument Object Model (DOM)Browser and Document StructureReading Properties with JavaScriptLanguage BasicsJavaScript BlocksJavaScript Primitive DatatypesObjectsFunctionsExamples of FunctionsAnonymous FunctionsBasic Object FeaturesJavaScript in Web PagesLanguage Features in This ClassStack Memory ManagementGarbage CollectionClosuresExceptionsObject featuresConcurrencyJavaScript evalUnusual Features of JavaScriptslide 1Vitaly ShmatikovCS 345Introduction to JavaScriptslide 2What’s a Scripting Language?Language used to write programs that compute inputs to another language processor•One language embedded in another–Embedded JavaScript computes HTML input to the browser–Shell scripts compute commands executed by the shellCommon characteristics of scripting languages•String processing – since commands often strings•Simple program structure, define things “on the fly”•Flexibility preferred over efficiency, safety–Is lack of safety a good thing? (Example: JavaScript used for Web applications…)slide 3Why JavaScript?“Active” web pagesWeb 2.0•AJAX, huge number of Web-based applicationsSome 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, …Many security and correctness issues“The world’s most misunderstood prog. language”slide 4JavaScript HistoryDeveloped by Brendan Eich at Netscape •Scripting language for Navigator 2Later standardized for browser compatibility•ECMAScript Edition 3 (aka JavaScript 1.5)Related to Java in name only•“JavaScript is to Java as carpet is to car”•Name was part of a marketing dealVarious implementations available•SpiderMonkey C implementation (from Mozilla)•Rhino Java implementation (also from Mozilla)slide 5Motivation for JavaScriptNetscape, 1995 •> 90% browser market share–“I hacked the JS prototype in ~1 week in May and it showed! Mistakes were frozen early. Rest of year spent embedding in browser” -- Brendan Eich, ICFP talk, 2006Design goals•Make it easy to copy/paste snippets of code•Tolerate “minor” errors (missing semicolons)•Simplified onclick, onmousedown, etc., event handling •Pick a few hard-working, powerful primitives–First-class functions, objects everywhere, prototype-based•Leave all else out!slide 6Common Uses of JavaScriptForm validationPage embellishments and special effectsNavigation systemsBasic math calculationsDynamic content manipulationSample applications•Dashboard widgets in Mac OS X, Google Maps, Philips universal remotes, Writely word processor, hundreds of others…slide 7Example 1: Add Two Numbers<html> … <p> … </p><script>var num1, num2, sumnum1 = prompt("Enter first number")num2 = prompt("Enter second number")sum = parseInt(num1) + parseInt(num2)alert("Sum = " + sum)</script>…</html>slide 8Example 2: Browser Events<script type="text/JavaScript"> function whichButton(event) {if (event.button==1) {alert("You clicked the left mouse button!") }else {alert("You clicked the right mouse button!") }}</script>…<body onmousedown="whichButton(event)">…</body>Mouse event causes page-defined function to be called Other events: onLoad, onMouseMove, onKeyPress, onUnLoadslide 9Example 3: Page ManipulationSome possibilities•createElement(elementName)•createTextNode(text)•appendChild(newChild)•removeChild(node)Example: add a new list item var list = document.getElementById('t1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext)This uses the browser Document Object Model (DOM). We will focus on JavaScript as a language, not its use in the browserDocument Object Model (DOM)HTML page is structured dataDOM provides representation of this hierarchyExamples•Properties: document.alinkColor, document.URL, document.forms[ ], document.links[ ], document.anchors[ ], …•Methods: document.write(document.referrer)–These change the content of the page!Also Browser Object Model (BOM)•Window, Document, Frames[], History, Location, Navigator (type and version of browser)slide 10Browser and Document Structure W3C standard differs from models supported in existing browsersslide 11slide 12Reading Properties with JavaScriptSample script•Example 1 returns "ul"•Example 2 returns "null"•Example 3 returns "li"•Example 4 returns "text"–A text node below the "li" which holds the actual text data as its value•Example 5 returns " Item 1 " 1. document.getElementById('t1').nodeName2. document.getElementById('t1').nodeValue3. document.getElementById('t1').firstChild.nodeName4. document.getElementById('t1').firstChild.firstChild.nodeName5. document.getElementById('t1').firstChild.firstChild.nodeValue<ul id="t1"><li> Item 1 </li></ul>Sample HTMLslide 13Language BasicsJavaScript is case sensitive•onClick, ONCLICK, … are HTML, thus not case-sensitiveStatements terminated by returns or semi-colons •x = x+1; same as x = x+1“Blocks” of statements enclosed in { …}Variables•Define using the var statement•Define implicitly by its first use, which must be an assignment–Implicit defn has global scope, even if occurs in nested scope!slide 14JavaScript BlocksUse { } for grouping; not a separate scopejs> var x=3;js> x3js> {var x=4; x}4js> x4Not blocks in the sense of other languagesslide 15JavaScript Primitive DatatypesBoolean: true and falseNumber: 64-bit floating point•Similar to Java double and Double •No integer type •Special values NaN (not a number) and InfinityString: sequence of zero or more Unicode chars•No separate character type (just strings of length 1)•Literal strings using ' or " characters (must match)Special objects: null and undefinedslide 16ObjectsAn object is a collection of named propertiesThink of it as an associative array or hash table•Set of name:value pairs–objBob = {name: “Bob", grade: 'A', level: 3};•Play a role similar to lists in Lisp / SchemeNew members can be added at any


View Full Document

UT CS 345 - Introduction to JavaScript

Download Introduction to JavaScript
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Introduction to JavaScript and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Introduction to JavaScript 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?