An Introduction to JavaScript

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.
Introducing JavaScript
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
The Web Warrior Guide to Web Design Technologies
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Introduction to Scripting.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
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.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
Introduction to Ruby CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341.
CST JavaScript Validating Form Data with JavaScript.
Taking JavaScript Seriously IS NOT THE WORST IDEA.
4.1 JavaScript Introduction
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
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.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
Introduction to JavaScript 11 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 14.
J AVA S CRIPT Shadi Banitaan 1. O UTLINE Introduction JavaScript Functions Using Objects in JavaScript Built-in Objects User-Defined Objects Examples.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Week 9 PHP Cookies and Session Introduction to JavaScript.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Lecture 9 The Basics of JavaScript Boriana Koleva Room: C54
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.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
JS Basics 1 Lecture JavaScript - Basics. JS Basics 2 What is JavaScript JavaScript is a “simple”, interpreted, programming language with elementary object-
ALBERT WAVERING BOBBY SENG. Week 4: JavaScript  Quiz  Announcements/questions.
Client-side processing in JavaScript.... JavaScript history Motivations –lack of “dynamic content” on web pages animations etc user-customised displays.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
1 JavaScript in Context. Server-Side Programming.
“The world’s most misunderstood language has become the world’s most popular programming language” Akshay Arora
1 Javascript CS , Spring What is Javascript ? Browser scripting language  Dynamic page creation  Interactive  Embedded into HTML pages.
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.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Expressions and Data Types Professor Robin Burke.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
CGS 3066: Web Programming and Design Spring 2016 Introduction to JavaScript.
JavaScript and Ajax Week 10 Web site:
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript: Good Practices
Chapter 4 Client-Side Programming: the JavaScript Language
JavaScript Syntax and Semantics
JavaScript Introduction
Web Systems Development (CSC-215)
CS5220 Advanced Topics in Web Programming JavaScript Basics
CS3220 Web and Internet 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:

An Introduction to JavaScript Godmar Back

JavaScript – The Basics Standardized as ECMAScript 262 Combines elements of functional, object-based, and object-oriented languages Dynamically typed Typesafe & Garbage collected Interpreted Weak typing in that both implicit and explicit type coercions are allowed Uses static scoping with run-time dependent bindings C-like syntax

Type System Types Values Number Type String Type Boolean Type Null Type Undefined Type Object Type IEEE FP Numbers Unicode Strings true, false null undefined objects, arrays, and functions

Operators Mostly like C or Java String concatenation via “+” Equality (==) Performs conversions Compares strings char-wise undefined == null Not transitive Identity (===, !==) Weird artifacts ("0" == false && !"0" == false) is ? && and || don’t always return Boolean, but type of last evaluated argument – type of (a && b) depends on value, not just type of a!

JavaScript Objects Objects are bundles of properties Properties can be of any type A property that’s a function can be viewed as a method of the object Property can be added by simple assignment a.x = 5 a.m = function () { …. } a.o = { p1: “string” } Properties can be deleted via ‘delete’ operator delete a.x Objects can be specified as literals { } “JSON” – JavaScript object notation has become an interchange format

JavaScript Scoping Static scopes: Does not use block { } scoping Properties of Global Object (default scope) Function scopes (one per nested function) – form a scope chain for “var” declarations Does not use block { } scoping All “var” declared variables with function are visible on entry (multiple var are silently ignore0 Variables initialized to ‘undefined’ As are missing function arguments Object literals do not create a new scope Object properties are *not* on scope chain E.g., ‘x’ does not resolve to ‘this.x’ within object method

JavaScript Functions First class objects Support closures Free variables resolve based on the scope chain in effect when function was defined Example: // some context in which ‘d’ is defined var f = function (a, b) { var c = 1; d = a + b + c; } Here, ‘d’ is bound as per scope chain in ‘some context’ Frequently used

What does this program output? function fiveguys() { var a = []; for (var i = 0; i < 5; i++) { a.push(function () { return i; }); } return a; f = fiveguys(); for (var i = 0; i < f.length; i++) println(f[i]()); Leads to frequent errors when passing closures to handle future events, e.g. AJAX responses

The ‘new’ operator JavaScript does not support class keyword, or concept (though will be added in next revision of language) Instead, new is applied to a function Creates empty object Invokes the function (“this” refers to the object during the call) Returns a new object Function object becomes the “.constructor” property Consequence any runtime instance of a function can “double” as a constructor (and thus define a type in the conventional sense)

Built-in Objects Function (type: function) Array (type: function) new Function("x", "return x * x")(2) -> 4 Array (type: function) [ ] initializer convenience syntax Arrays are sparse, length is (max {index} + 1) Number (type: function) – type coercion String (type: function) – type coercion Boolean (type: function) – type coercion Date RegExp Math

Prototypical Inheritance Let function F() { } Let F.prototype = { <properties a, b, c> } Then o = new F() means reading o.a reads F.prototype.a but writing o.a does not affect F.prototype after write, subsequent reads will read per-object property Result: (somewhat) like dynamic classes: adding/removing properties to prototype object affects all “instances” created based on the prototype Recursively – forms prototype chain Can be used to implement traditional inheritance

‘this’ Binding depends on context At top-level, ‘this’ is the global object Inside functions, it depends on how the function is called: If called via ‘new’ or using dot operator a.f(), ‘this’ is the current object Else ‘this’ is the global object This (no pun intended) is confusing and extremely error prone Can use .bind() to create function with fixed ‘this’

What does this program output? // redundant, just for illustration prop = undefined; obj = { prop : "mine", // a "field" method: function () { // a "method“ println("this.prop = " + this.prop); helper(); // a nested function within a method function helper () { } obj.method(); m = obj.method; m();

Real-life JavaScript JavaScript is embedded in environments Most notably: in web pages Global object here has additional properties E.g., “window” (alias for global object) “document”, “alert”, “setTimeout”, etc. Allows interaction with the page, viewed as a hierarchical tree – the “DOM” referred to by “document” Lots of “ad-hoc” code, but most new code is structured 2 Trends for structuring jQuery – style – not OO, but DOM-centered OO-style JavaScript Use prototypical facilities to superimpose classic OO concepts, such as packages, inheritance, and mix-ins

jQuery The entire library is contained in a single function called “$” $(document).ready(function() { $("a").click(function(event) { alert("Thanks for visiting!"); }); The entire library is contained in a single function called “$” returns a “selector” object that represents subset of elements in DOM and has chainable methods to operate on them (“for all”)

OO-style JavaScript Some codes use “manual” inheritance More common: Declare functions, name them, add prototype property, etc. – tedious, but amenable to static analysis because at least ‘function’ types are declared More common: Classes are created on the fly using factory methods, e.g. libx.core.Class.create() Example: http://libx.org/libx-new/src/editions/doc/symbols/src/libx2_base_vector.js.html

Sources of Errors Sheer confusion about scoping Defaulting to global scope means “for (i = 0; i < 10; i++)” clobbers global i ‘this’ Namespace pollution (like globals in C) “Helpful” code that changes prototype chains of all objects, e.g. “Object.prototype.usefulmethod = “ Aliases (as in other OO languages) Assigning a.x creates a local property, != b.x Assigning a.x.y may be the same as b.x.y. Closures (see earlier example)

JavaScript Security JavaScript executes in Sandbox No access to file system, etc. JavaScript has full access to the DOM of the current page As well as to DOM of pages loaded from the same domain - can transform it in any way Cross-site scripting attack Inject JavaScript into page by tricking server to serve it: via email, or post to form, etc. Implication for including third party code Saying <script src=“http://somedomain.com” /> requires that you trust somedomain.com entirely – all or nothing No stack inspection

JavaScript & Concurrency JavaScript is single-threaded Current event-handler runs to completion Consequence: JavaScript must not run for “too long” JavaScript code must not “block” – e.g., no synchronous network I/O Forces continuation-passing style Great potential for concurrency bugs – execution order of network completion handlers is random May even be synchronous if result is cached! Plus, for big pages, execution of inlined JS is not uninterrupted and may interleave with event handlers These errors are typically missed during testing

Further Pointers ECMA-262: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf Flanagan's JavaScript book, Chapters 1-4, available here – VT internal link: http://proquest.safaribooksonline.com/?uiCode=vatech&xmlId=0596101996 Doug Crockford's pages make for easy and concise reading: http://www.crockford.com/javascript/