1 / 83

JavaScript: A Smart Prototype-based Scripting Language

JavaScript is a dynamic and versatile scripting language that is supported by most browsers. It allows you to add content to web pages, interact with users, manipulate cookies, and more. Discover its features, security measures, language elements, and how to use it in HTML documents.

donetta
Download Presentation

JavaScript: A Smart Prototype-based Scripting Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript Prototype-basedscripting language

  2. Smart Browsers • Most browsers support a <SCRIPT> tag that is used to include executable content in an HTML document. • There are a number of scripting languages that are supported

  3. Client-Side Script Languages • Netscape and others • JavaScript • Internet Explorer • Jscript (MS name for JavaScript) • VBScript • PerlScript

  4. JavaScript Capabilities • Add content to a web page dynamically. • Alter a web page in response to user actions. • React to user events. • Interact with frames. • Manipulate HTTP cookies

  5. JavaScript is not Java • JavaScript is a very simple scripting language. • Syntax is similar to a subset of Java. • Interpreted language. • Uses objects, but doesn't really support the creation of new object types* *It almost does, but it's cumbersome.

  6. Features • Imperative and structured • Dynamic 1.dynamic typing: As in most scripting languages, types are associated with values, not with variables. For example, a variable x could be bound to a number, then later rebound to a string. JavaScript supports various ways to test the type of an object, including duck typing. 2.run-time evaluation: JavaScript includes an evalfunction that can execute statements provided as strings at run-time.

  7. Functional closures JavaScript allows nested functions to be created, with the lexical scope in force at their definition, and has a () operator to invoke them now or later. This combination of code that can be executed outside the scope in which it is defined, with its own scope to use during that execution, is called a closure in computer science

  8. Security • JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using restrictions. scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.

  9. Language Elements • Variables • Literals • Operators • Control Structures • Objects

  10. JavaScript Variables • Untyped! • Can be declared with var keyword: var foo; • Can be created automatically by assigning a value: foo=1; blah="Hi Eve";

  11. Variables (cont.) • Using var to declare a variable results in a local variable (inside a function). • If you don't use var – the variable is a global variable.

  12. Literals • The typical bunch: • Numbers 17 123.45 • Strings "Hello Eve" • Boolean: true false • Arrays: [1,"Hi Eve",17.234] Arrays can hold anything!

  13. Operators • Arithmetic, comparison, assignment, bitwise, Boolean + - * / % ++ -- == != > < && || ! & | << >>

  14. Control Structures if if-else ?: switch for while do-while • And a few not in C for (var in object) with (object)

  15. Objects • Objects have attributes and methods. • Many pre-defined objects and object types. • Using objects follows the syntax of C++/Java: objectname.attributename objectname.methodname()

  16. Array Objects • Arrays are supported as objects. • Attribute length • Methods include: concat join pop push reverse sort

  17. Array example code var a = [8,7,6,5]; for (i=0;i<a.length;i++) a[i] += 2; b = a.reverse();

  18. Many other pre-defined object types • String: manipulation methods • Math: trig, log, random numbers • Date: date conversions • RegExp: regular expressions • Number: limits, conversion to string

  19. Predefined Objects • JavaScript also includes some objects that are automatically created for you (always available). • document • navigator • screen • window

  20. The document object • Many attributes of the current document are available via the document object: Title Referrer URL Images Forms Links Colors

  21. document methods • document.write() like a print statement – the output goes into the HTML document. document.write("My title is" + document.title); string concatenation!

  22. JavaScript Example <HEAD> <TITLE>JavaScript</TITLE> </HEAD> <BODY> <H3>I am a web page and here is my name:</H3> <SCRIPT> document.write(document.title); </SCRIPT> <HR>

  23. JavaScript andHTML Comments <SCRIPT> <!-- document.write("Hi Eve"); document.bgColor="BLUE"; --> </SCRIPT> HTML comment

  24. JavaScript Functions • The keyword function used to define a function (subroutine): function add(x,y) { return(x+y); }

  25. JavaScript Events • JavaScript supports an event handling system. • You can tell the browser to execute javascript commands when some event occurs. • Sometimes the resulting value of the command determines the browser action.

  26. Simple Event Example <BODY BGCOLOR=WHITE onUnload="restore()"> <H5>Hello - I am a very small page!</H5> <SCRIPT> savewidth = window.innerWidth; saveheight = window.innerHeight; function restore() { window.innerWidth=savewidth; window.innerHeight=saveheight; } // Change the window size to be small window.innerWidth=300; window.innerHeight=50; document.bgColor='cyan'; </SCRIPT>

  27. Buttons • You can associate buttons with JavaScript events (buttons in HTML forms) <FORM> <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')“ > </FORM>

  28. Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events

  29. Document Object Model • Naming hierarchy used to access individual elements of a HTML document. • Netscape D.O.M. is a little different than IE D.O.M. • Easy to use if you name all entities: • Forms, fields, images, etc. Things are getting better all the time – there are standard DOMs defined by The W3C

  30. DOM example <FORM ID=myform ACTION=… Please Enter Your Age: <INPUT TYPE=TEXT ID=age NAME=age><BR> And your weight: <INPUT TYPE=TEXT ID=weight NAME=weight><BR> </FORM> From javascript you can get at the age input field as: document.myform.age.value

  31. Form Field Validation • You can have JavaScript code that makes sure the user enters valid information. • When the submit button is pressed the script checks the values of all necessary fields: • You can prevent the request from happening.

  32. Checking Fields function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); } } Needs to return true or false!

  33. The Form Needed to prevent the browser from submitting! <FORM METHOD=GET ACTION=foo.cgi NAME=myform onSubmit="return(checkform())"> AGE: <INPUT TYPE=TEXT NAME=Age> <INPUT TYPE=SUBMIT> </FORM>

  34. Important Note about Form Validation • It's a good idea to make sure the user fills out the form before submitting. • Users can bypass your form – they can create requests manually (or their own forms). • Your CGI programs cannot rely (soley) on Client-Side JavaScript to validate form fields!

  35. Advantages of JavaScript • Speed. Being client-side, JavaScript is very fast because any code functions can be run immediately instead of having to contact the server and wait for an answer. • Simplicity. JavaScript is relatively simple to learn and implement. • Versatility. JavaScript plays nicely with other languages and can be used in a huge variety of applications. Unlike PHP or SSI scripts, JavaScript can be inserted into any web page regardless of the file extension. JavaScript can also be used inside scripts written in other languages such as Perl and PHP. • Server Load. Being client-side reduces the demand on the website server.

  36. Disadvantages of JavaScript • Security. Because the code executes on the users' computer, in some cases it can be exploited for malicious purposes. This is one reason some people choose to disable JavaScript. • Reliance on End User. JavaScript is sometimes interpreted differently by different browsers. Whereas server-side scripts will always produce the same output, client-side scripts can be a little unpredictable. Don't be overly concerned by this though - as long as you test your script in all the major browsers you should be safe.

  37. LUA

  38. Lua from Portuguese meaning " moon ") is a lightweight multi-paradigm programming language designed as a scripting language with extensible semantics as a primary goal. Lua has a relatively simple C API compared to other scripting languages

  39. Lua is a powerful, fast, lightweight, embeddable scripting language. Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting byte code for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping.

  40. Lua's historical 'father and mother' were data-description/configuration languages SOL (Simple Object Language) and DEL (data-entry language). They had been independently developed at Tecgraf in 1992-1993 to add some flexibility into two different projects (both were interactive graphical programs for engineering applications at Petro bras company).

  41. Features/ Characteristics • Multi-paradigm language • does not contain explicit support for inheritance • easily with meta tables • implement namespaces and classes • first-class functions • functional programming

  42. Advantages of Lua • Lua is fastest language • Lua is portable • Lua is embeddable • Lua is powerful (but simple) • Lua is free open-source software

  43. Disadvantages of Lua • An inherent is that it’s a fairly rarely-used language. • An implementation is that it currently dependent on an external Lua binary installation

  44. Data Types • Boolean values • numbers (double-precision floating point by default) • strings. Typical data: • Arrays, sets, lists, and records can be represented using Lua’s single native data structure, the table, which is essentially a heterogeneous associative array Data Type

  45. Example • Literals and output in Lua print ('1: Hello World')print ("2: Hello World") The Result: 1: Hello World2: Hello World

  46. A simple array of strings array = { "a", "b", "c", "d" } print(array[2]) print(#array) array[0] = "z" print(#array) • An array of objects: function Point(x, y) return { x = x, y = y } end array = { Point(10, 20), Point(30, 40), Point(50, 60) } print(array[2].y)

  47. Creating a basic vector object Vector = {} the class methods function Vector:new(x, y, z local object = { x = x, y = y, z = z } setmetatable(object, { __index = Vector }) return object End function Vector:magnitude() return math.sqrt(self.x^2 + self.y^2 + self.z^2) end vec = Vector:new(0, 1, 0) print(vec:magnitude ()) print(vec.x)

  48. Loops • For-loop for variable = 0, 10, 2 do print ( variable ) end Loops: • While-loop: i = 1while i <= 5 do print (i) i = i + 1 end

  49. Lua Examples • A very simple configuration file: width = 420 height = width*3/2 -- ensures 3/2 aspect ratio color = "blue

  50. Another Example • A configuration file using Functions: function Bound (w, h) if w < 20 then w = 20 elseif w > 500 then w = 500 end local minH = w*3/2 -- local variable if h < minH then h = minH end return w, h end width, height = Bound(420, 500) if monochrome then color = "black" else color = "blue" end

More Related