Javascript. Many examples from Kyle Simpson: Scope and Closures

Similar documents
Recall: Document Object Model (DOM)

Web Programming Step by Step

Indian Institute of Technology Kharagpur. Javascript Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Best Practices Chapter 5

INF5750. Introduction to JavaScript and Node.js

JavaScript: Events, the DOM Tree, jquery and Timing

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

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

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

Web Programming Step by Step

CSE 154 LECTURE 10: THE DOM TREE

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

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript Specialist v2.0 Exam 1D0-735

JavaScript. The Bad Parts. Patrick Behr

JavaScript CS 4640 Programming Languages for Web Applications

CSC Web Programming. JavaScript Browser Objects

JavaScript: the language of browser interactions. Claudia Hauff TI1506: Web and Database Technology

AJAX: The Basics CISC 282 March 25, 2014

JavaScript: Sort of a Big Deal,

AJAX: The Basics CISC 282 November 22, 2017

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

Session 6. JavaScript Part 1. Reading

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

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

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

JavaScript 3. Working with the Document Object Model (DOM) and DHTML

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

CS312: Programming Languages. Lecture 21: JavaScript

5/19/2015. Objectives. JavaScript, Sixth Edition. Understanding the Browser Object Model and the Document Object Model. Objectives (cont'd.

ADDING FUNCTIONS TO WEBSITE

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum

EECS1012. Net-centric Introduction to Computing. Lecture JavaScript DOM

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

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

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

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

DOM. Ajax Technology in Web Programming. Sergio Luján Mora. DLSI - Universidad de Alicante 1. API for accessing and manipulating HTML documents

Ajax. Ronald J. Glotzbach

Background. Javascript is not related to Java in anyway other than trying to get some free publicity

5. Strict mode use strict ; 6. Statement without semicolon, with semicolon 7. Keywords 8. Variables var keyword and global scope variable 9.

Boot Camp JavaScript Sioux, March 31, 2011

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

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

ECMAScript 2015 The Future of JavaScript is Now!

JavaScript Introduction

Notes on JavaScript (aka ECMAScript) and the DOM

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains an Individual and Group component

Node.js Training JavaScript. Richard richardrodger.com

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

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

FALL 2017 CS 498RK JAVASCRIPT. Fashionable and Functional!

Web Development. HCID 520 User Interface Software & Technology

Sample CS 142 Midterm Examination

JavaScript Pocket Reference, 2nd Edition By David Flanagan. Publisher: O'Reilly Pub Date: October 2002 ISBN: Pages: 136 Slots: 0.

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

Lecture 8 (7.5?): Javascript

JavaScript: Introduction, Types

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Lecture 17. History, Navigator, Screen and Form Objects. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Index. Ray Nicholus 2016 R. Nicholus, Beyond jquery, DOI /

Overview. Elements of Programming Languages. Objects. Self-Reference

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

Writing robust client-side code using Modern JavaScript or JavaScript: the Good, the Bad, the Strict and the Secure Parts

JavaScript for C# Programmers Kevin

CGS 3066: Spring 2015 JavaScript Reference

Session 16. JavaScript Part 1. Reading

Comprehensive AngularJS Programming (5 Days)

Extensible Markup Language (XML) What is XML? Structure of an XML document. CSE 190 M (Web Programming), Spring 2007 University of Washington

CSC Web Programming. Introduction to JavaScript

XML: a "skeleton" for creating markup languages you already know it! <element attribute="value">content</element> languages written in XML specify:

Web Application Development

Client Side JavaScript and AJAX

INDEX SYMBOLS See also

XML CSC 443: Web Programming

Javascript Arrays, Object & Functions

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Javascript Hierarchy Objects Object Properties Methods Event Handlers. onload onunload onblur onfocus


Client-Side Web Technologies. JavaScript Part I

The attributes property of an element node returns a list of attribute nodes. It s called a named node map

COMP-520 GoLite Tutorial

Project 3 Web Security Part 1. Outline

Client vs Server Scripting

JavaScript: the Big Picture

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

JavaScript or: HOW I LEARNED TO STOP WORRYING AND LOVE A CLASSLESS*

JavaScript I Language Basics

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

ECMAScript 6 The Future of JavaScript is Now!

jquery Tutorial for Beginners: Nothing But the Goods

Working with JavaScript

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

JavaScript Lecture 1

Sebastiano

Brief Intro to Firebug Sukwon Oh CSC309, Summer 2015

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

Programming language components

Walking the DOM Tree. Lecture Outline. An example XHTML page. CSE 190 M (Web Programming), Spring 2008 University of Washington

Transcription:

Javascript Many examples from Kyle Simpson: Scope and Closures

What is JavaScript? Not related to Java (except that syntax is C/Java- like) Created by Brendan Eich at Netscape later standardized through ECMA ECMAScript3 in 1999 is the baseline for modern day JS Microsoft showed no intention of implementing proper JS in IE stalled progress on ES4 2005 work restarted on ECMAScript 4 amid continued controversy

What is JavaScript? 2005 Jesse James Garrett s white paper coined the term Ajax web apps could load data in the background led to the development of JQuery, Prototype, Dojo ES6 came out in 2015 See http://kangax.github.io/compat-table/es6/ for browser compatibility

JavaScript Engines An engine is the program that interprets and executes JavaScript code V8 - Google s open source engine used in Chrome and Node Spidermonkey - Mozilla JavaScriptCore (Nitro, Squirrelfish) - Safari, Webkit Chakra - MS Edge

Transpilers Transpiler = source-to-source compiler Babel - ES6 (ES2015 to ES5) allows you to write ES6 JS without worrying about browser compatibility problems. CoffeeScript TypeScript ClojureScript

Language highlights Many things are as you would expect from your experience with Python, C and Java We will focus on features that are not quite what you might expect Always use strict ;

Scoping Rules a = 3; // global scope var b = 3; // global scope function foo() { c = 10 // global var d = 5; // function scope (lexical) function nested() { d = 6; // function (foo) scope console.log(d);

use strict ; var a = 3; // global scope var b = 3; // global scopes function foo() { var c = 10 // function scope var d = 5; // function scope function nested() { var d = 6; // function scope console.log(d);

ES6 use strict ; var a = 3; // global scope var b = 3; // global scope function foo() { let c = 10 // block let d = 5; // block scope function nested() { let d = 6; // block scope console.log(d); let gives you block scope rather than function scope

Hoisting foo(); // 1 var foo; function foo() { console.log( 1 ); // But why would you do this? // Strange behaviour

Hoisting tip Declare variables at the top of your function. Easier to read Avoids strange behaviour attributable to hoisting

Functions are first-class objects var sq = function(x) { return x * x; function cube(x) { return x * x * x;

Anonymous functions var sq = function(x) { ; return x * x; // If you can give a brief descriptive // name you should for readability

IIFE Immediately Invoked Function Expressions var a = 2; var a = 2; function foo() { var a = 3; console.log(a); foo(); console.log(a); (function foo() { var a = 3; console.log(a); )(); console.log(a); Quiz: What if we removed var everywhere?

Naming anonymous functions? settimeout( function(){ console.log( "I waited 1 second!" );, 1000); No function name to display in stack traces Can t refer to itself for recursion or unbinding and event handler A name helps self-document the code

Naming anonymous functions? settimeout( function timeouthandler(){ console.log( "I waited 1 second!" );, 1000);

Closures Closures happen as a result of writing code that relies on lexical scope. Kyle Simpson An unsurprising result of first-class objects and lexical scope..

Normal code function foo() { var a = 2; function bar() { console.log( a ); // 2 bar(); foo();

Closure function foo() { var a = 2; function bar() { console.log( a ); // 2 return bar; Effectively carries its lexical scope with the function reference var baz = foo(); baz();

Another example function foo() { var a = 2; function baz() { console.log( a ); // 2 bar( baz ); function bar(fn) { fn();

For real function wait(message) { settimeout( function timer(){ console.log( message );, 1000 ); wait( "Hello, closure!" ); // Implementation of settimeout has a call //to its parameter

Loops for (var i=1; i<=5; i++) { settimeout( function timer(){ console.log( i );, i*1000 ); //Output?

Loops: solution for (var i=1; i<=5; i++) { (function() { )(); settimeout( function timer(){ console.log( i );, i*1000 ); // Maybe if we wrap it in a new scope

Loops: attempt 2 for (var i=1; i<=5; i++) { (function() { )(); settimeout( function timer(){ console.log( i );, i*1000 ); // Maybe if we wrap it in a new scope The problem is there is only one i.

Loops: solution for (var i=1; i<=5; i++) { (function() { )(); var j = i; settimeout( function timer(){ console.log( j );, i*1000 );

Loops: even better for (var i=1; i<=5; i++) { let j = i; // block scope!! settimeout( function timer(){ console.log( j );, i*1000 );

Objects An object is a container of properties, where a property has a name and a value You can create object literals: var point = { x: 10, y: 20; var point = { x : 10, y : 20; Quotes are optional if the name would be a legal JS name object properties retrieved by point.x OR point[ x ]

Methods on Objects function dist_from_orig() { console.log(this.x); return(math.sqrt(this.x * this.x + this.y* this.y)); var p1 = { x: 10, y: -6, dist_from_orig: dist_from_orig ; console.log(p1.dist_from_orig());

Function Objects/ Constructors function dist_from_orig() { console.log(this.x); return(math.sqrt(this.x * this.x + this.y* this.y)); function Point(x, y) { this.x = x; this.y = y; this.dist = dist_from_orig; var p3 = new Point(3,2); console.log(p3.dist_from_orig);

Adding properties var p3 = new Point(3,2); p3.is_origin = function is_origin() { return this.x == 0 && this.y == 0; p3.z = 33; if(p3.is_origin()) { console.log("origin"); else { console.log("not orgin");

this Mostly works as you would expect, but is really different than other programming languages. It refers to the containing object of the call-site of a function, not where the function is defined. Under use strict the global object is not eligible for this binding.

Implicit Binding function bar() { console.log(this.a); var obj2 = { a: 42, bar: bar ; var obj1 = { a: 2, obj2: obj2 obj2.bar(); obj1.obj2.bar(); What is the result of these calls? What would you expect? Try running it!

Lost binding var p = obj1.bar; p(); // undefined This happens because obj1.bar is just a reference, it doesn t belong to obj1.

Explicit binding bar.call(obj1); // 2 Forces this to be obj1

new binding function Point(x, y) { this.x = x; this.y = y; this.dist = dist_from_orig; var p3 = new Point(3,2);

DOM

DOM - Document Object Model Document Root Element <html> Element: <head> Element: <body> Element: <title> Attribute: href Element: <a> Element: <h1> Text: My Title Text: A link Element: A header

BOM: Browser Object Model Name Description Not standardized, so each browser may be different document DOM (current HTML page) history location navigator screen window List of pages user has visited URL of current page Info about the browser Screen area (viewport) occupied by the browser. The browser window

window Top level object in the Browser Object Model Methods include: alert, confirm, prompt (popup boxes) setinterval, settimeout clearinterval, cleartimeout (timers) open, close (popping up new browser windows) blur, focus, moveby, moveto, print, resizeby, resizeto, scrollby, scrollto

document Current web page and its elements Properties: anchors, body, cookie, domain, forms, images, links, referrer, title, URL Methods: getelementbyid getelementsbyname getelementsbytagname close, open, write, writeln

Location: URL of the current page Properties: host, hostname, href, pathname, port, protocol, search Methods: assign, reload, replace Navigator: Information about the web browser Properties: appname, appversion, browserlanguage, cookieenabled, platform, useragent

Screen : information about the display screen Properties: availheight, availwidth, colordepth, height, pixeldepth, width Difference? Screen is what s visible to you Window is the browser window including scrollbars, navigation, bookmark bars, etc Document can be larger than the screen/window

The history object keeps a list of sites that the browser has visited in this window. Properties: length Methods: back, forward, go Sometimes the browser won't let scripts view history properties, for security reasons.

Name firstchild lastchild Description Start/end of this node s list of children. childnodes Array of all this node s children nextsibling previoussibling Neighbouring nodes with the same parent. parentnode Node that contains this node

<p> This is a paragraph with a <a href= /path/page.html >link</a> in it.s </p> p parentnode firstchild This is a paragraph with a firstchild a link lastchild lastchild in it.

Name document. createelement( tag ) document. createtextnode( text ) appendchild(node) insertbefore(new, old) removechild(node) replacechild(new, old) Description Create and return a new empty DOM nodes Create and return a text node with the given text place node at end of this node s children place given new node just before old child remove node from this child list replace node