Boot Camp JavaScript Sioux, March 31, 2011

Similar documents
CS312: Programming Languages. Lecture 21: JavaScript

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

JavaScript: Sort of a Big Deal,

INF5750. Introduction to JavaScript and Node.js

JavaScript for C# Programmers Kevin

FALL 2017 CS 498RK JAVASCRIPT. Fashionable and Functional!

JavaScript Patterns O'REILLY* S toy an Stefanov. Sebastopol. Cambridge. Tokyo. Beijing. Farnham K8ln

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

JavaScript CS 4640 Programming Languages for Web Applications

Node.js Training JavaScript. Richard richardrodger.com

Javascript. Many examples from Kyle Simpson: Scope and Closures

Client-Side Web Technologies. JavaScript Part I

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

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

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

COMS 469: Interactive Media II

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

JavaScript CS 4640 Programming Languages for Web Applications

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

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

Busy.NET Developer's Guide to ECMAScript

JavaScript Doesn't Have to Hurt: Techniques, Tools and Frameworks to Ease JavaScript Development

Working with JavaScript

Part 1: jquery & History of DOM Scripting

COMS 469: Interactive Media II

Frontend II: Javascript and DOM Programming. Wednesday, January 7, 15

COMP 110 Practice Exercises for Midterm Solutions

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages

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

Advanced JavaScript. Konstantin Käfer. Konstantin Käfer

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

Lecture 8 (7.5?): Javascript

JavaScript for PHP Developers

JavaScript: Coercion, Functions, Arrays

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

Static Analysis for JavaScript

JavaScript: Features, Trends, and Static Analysis

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

JavaScript: the Big Picture

JavaScript Programming

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

Web Application Development

Part I: Introduction to Functions

JavaScript and V8 A functional-ish language and implementation in the mainstream

COP4020 Programming Assignment 1 - Spring 2011

CSE 341 Lecture 27. JavaScript scope and closures. slides created by Marty Stepp

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Client vs Server Scripting

JavaScript. What s wrong with JavaScript?

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

JavaScript Specialist v2.0 Exam 1D0-735

JavaScript: The Good Parts

JavaScript: The Definitive Guide

Introduction to Python programming, II

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

Scripting for Multimedia LECTURE 3: INTRODUCING JAVASCRIPT

arxiv: v1 [cs.pl] 15 Dec 2009

Chapter 4 Statements. Slides Modified by Vicky Seno

Functional JavaScript. Douglas Crockford Yahoo! Inc.

JavaScript: The Good Parts. Douglas Crockford Yahoo! Inc.

CSC Web Programming. Introduction to JavaScript

classjs Documentation

SEEM4570 System Design and Implementation Lecture 03 JavaScript

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

Javascript Tutorial With Example

Notes on JavaScript (aka ECMAScript) and the DOM

Course 2320 Supplementary Materials. Modern JavaScript Best Practices

Today. Continue our very basic intro to JavaScript. Lambda calculus

CSCI 1061U Programming Workshop 2. C++ Basics

JavaScript: Introduction, Types

CGS 3066: Spring 2015 JavaScript Reference

Client-side Debugging. Gary Bettencourt

JavaScript Programming

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

JavaScript: More Syntax

Introduction to Programming Using Java (98-388)

JavaScript I Language Basics

Project 5 Due 11:59:59pm Wed, July 16, 2014

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

The Art of Recursion: Problem Set 10

The JavaScript Language

This document defines the ActionScript 3.0 language, which is designed to be forward- compatible with the next edition of ECMAScript (ECMA-262).

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

JavaScript Lecture 1

A Structural Operational Semantics for JavaScript

Javascript : the language. accu2009 conference 25 th April 2009 Tony Barrett-Powell

JavaScript Introduction

JavaScript: The Basics


Qiufeng Zhu Advanced User Interface Spring 2017

Comprehensive AngularJS Programming (5 Days)


Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

For this chapter, switch languages in DrRacket to Advanced Student Language.

Transcription:

Boot Camp JavaScript http://rix0r.nl/bootcamp Sioux, March 31, 2011

Agenda Part 1: JavaScript the Language Short break Part 2: JavaScript in the Browser

History May 1995 LiveScript is written by Brendan Eich for NN2 Dec 1995 Renamed to JavaScript in a deal with Sun Aug 1996 Microsoft copies JScript for IE 3.0 Nov 1996 Netscape goes shopping for a standard Ecma ECMAScript Dec 1998 dynamicdrive.com Mar 1999 OWA team invents Xml.HTTP (IE 5.0) Dec 2000 Firefox copies XmlHttpRequest 2004 GMail Feb 2005 The term AJAX is invented 2005 Google Maps Apr 2006 XmlHttpRequest standardized renaissance JavaScript

Where?

Where?

Where?

Where?

Where?

Where?

Where?

Where?

Tooling support Firebug (Firefox) WebKit Console (Chrome, Safari)

Part 1 JavasScript the Language

Ancestry Functions from Scheme Prototypes from Self Syntax from Java Event-driven model from HyperCard

Types String "hello", 'world' Object { hello: 'world' } Number 1, 3.14, 2e11, NaN Array [1, 2, 3] Boolean true, false Function function(x) { return x*x; } null null undefined undefined

A little word about functions Functions are first-class! function greet() { alert('hi there!'); } Is the same as: var greet = function() { alert('hi there!'); }

Semicolon insertion function foo(x) { var y = x*2 return { x: x, y: y } } alert(foo(3)) //?

Semicolon insertion function foo(x) { var y = x*2 return { x: x, y: y } } ParseError! alert(foo(3)) //?

Semicolon insertion function foo(x) { var y = x*2 return; { x: x, y: y } } ParseError! alert(foo(3)) //?

Semicolon insertion function foo(x) { var y = x*2 return { x: x, y: y } } alert(foo(3)) // { x: 3, y: 6 } Use K&R style braces!

Objects & Prototyping

Objects Object is a property bag (dictionary): world['greeting'] = 'hello'; world.greeting = 'hello'; world = { greeting: 'hello' }; Methods are simply values that happen to be callable: world.greet = function(hello) { alert(hello + ' world!'); }; world.greet('cheerio');

Objects are open All object members can always be replaced. How does a method know on which object it is invoked? (Answer: this) earth.age = 4e9; earth.birthday = function() { this.age++; }; earth.birthday(); // 4000000001

Exercise 1 Add a sum() method to an array http://rix0r.nl/bootcamp Hints: Use this to refer to the current object. Array iteration: for (var i = 0; i < array.length; i++) { alert(array[i]); }

this is dynamically bound :) Same birthday, different object. dog.age = 2; dog.birthday = earth.birthday; dog.birthday(); alert(dog.age); // 3 Bound at moment of invocation.

this is dynamically bound :( Only if you call object.method() exactly: dog.age = 3; dog_birthday = dog.birthday; dog_birthday(); alert(dog.age); //? alert(age); //?

this is dynamically bound :( Only if you call object.method() exactly: dog.age = 3; dog_birthday = dog.birthday; dog_birthday(); alert(dog.age); //? 3 alert(age); //?

this is dynamically bound :( Only if you call object.method() exactly: dog.age = 3; dog_birthday = dog.birthday; dog_birthday(); alert(dog.age); //? 3 alert(age); //? NaN ( undefined + 1 ) (Should have been ReferenceError)

this is dynamically bound :( Only if you call object.method() exactly: dog.age = 3; dog_birthday = dog.birthday; dog_birthday(); alert(dog.age); //? 3 alert(age); //? NaN ( undefined + 1 ) (Should have been ReferenceError) We ll see a solution later on!

JavaScript Object Pattern Invoke a function with new, and it gets called on a new object (as the constructor): function Dog(name) { this.age = 0; this.name = name; } var pooch = new Dog('pooch'); alert(pooch.age); // 0

Prototyping Mechanism for code reuse. No classes. (But you can emulate classes if you want to)

Prototype chain (prototype) name (prototype) "earth" name greet "world" function () { alert("hello " + this.name); } age 4.5E9 earth.greet(); // "Hello earth"

Setting the prototype prototype attribute of constructor function: World.prototype.greet = /*... */; Earth.prototype = new World(); var earth = new Earth(); earth.greet(); The prototype of the object is set to whatever the prototype attribute of the Earth function points to.

Exercise 2 The Counter object Write a constructor for an object that will return sequential numbers. Hints: Initialize the object in the constructor. Use the prototype to share methods between objects.

Setting the prototype, the old way prototype World() name greet "world" function () { alert("hello " + this.name); } new World() prototype Earth() new Earth() name "earth"

Setting the prototype, the old way Useless extra object in the inheritance chain. If you forget new, it s a regular function call and won t do what you want! Assignments to Function.prototype.whatever are quite ugly.

Setting the prototype, the new way Object.create(proto, properties): var world = { name: 'world', greet: /*... */ }; var earth = Object.create(world, { name: 'earth' }); earth.greet(); // Hello earth

Setting the prototype, the new way (prototype) name (prototype) "earth" name greet "world" function () { alert("hello " + this.name); } age 4.5E9

Prototypes are open Prototypes are just objects, and hence open as well! Which object is the prototype cannot be changed after instantiation, but the members of the prototype can!

Exercise 3 Monkey patching Adding useful methods to built-ins like String or Array. (In this case, add the sum() method from exercise 1 to all arrays) Used a lot by JavaScript libraries to paper over browser incompatibilities! (For example, Array.forEach()...)

Advantages of prototyping Lightweight and flexible Some patterns are much easier with prototypes (factory, prototype (*), decorator,...) Prototypes can emulate classes but not the other way around! (*) Well duh!

Functions & Closures

Functions Functions are first-class Functions are functions Functions are methods Functions are constructors Functions define scope

Scope By default, everything goes in the global object. No modules! Undeclared variables go in global scope! Only function scope exists. this is dynamically bound.

Undeclared variables go in global scope function foo() { a = 1; } function bar() { alert(a); } foo(); bar(); //?

Undeclared variables go in global scope function foo() { a = 1; } function bar() { alert(a); } foo(); bar(); //? 1

Undeclared variables go in global scope function foo() { var a = 1; } function bar() { alert(a); } foo(); bar(); //?

Undeclared variables go in global scope function foo() { var a = 1; } function bar() { alert(a); } foo(); bar(); //? ReferenceErrror

Undeclared variables go in global scope function foo() { var a = 1; } function bar() { alert(a); } foo(); bar(); //? ReferenceErrror Always use var!

Function scope var a = 1; function foo() { alert(a); //? var a = 2; alert(a); //? } foo();

Function scope var a = 1; function foo() { alert(a); //? var a = 2; alert(a); //? } 2 foo();

Function scope var a = 1; function foo() { alert(a); //? var a = 2; alert(a); //? } ReferenceErrror 2 foo();

Closures Functions retain references to the environment of their definition var make_greeter = function(greeting) { return function(who) { alert(greeting + ' ' + who); } }; var briton = make_greeter('cheerio'); briton('mate'); // Cheerio mate briton('old chap'); // Cheerio old chap

Closures Functions retain references to the environment of their definition var make_greeter = function(greeting) { return function(who) { alert(greeting + ' ' + who); } }; var briton = make_greeter('cheerio'); briton('mate'); // Cheerio mate briton('old chap'); // Cheerio old chap

Immediately invoked functions = modules var days = (function() { var names = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; return { name: function(nr) { return names[nr]; }, nr: function(nm) { return names.indexof(nm); } }; }()); alert(days.name(3)); // 'Thu' alert(days.nr('thu')); // 3

Exercise 4 Closures can emulate objects Rewrite the Counter object from exercise 2 as a closure. Hint: An outer function creates a scope with private variables and returns an inner function that provides access to this scope.

Closures close over variables, not values var funcs = []; for (var i = 0; i < 10; i++) { funcs.push(function() { alert(i); }); } funcs[0](); //??

Closures close over variables, not values var funcs = []; for (var i = 0; i < 10; i++) { funcs.push(function() { alert(i); }); } funcs[0](); //?? 10

Closures close over variables, not values var funcs = []; for (var i = 0; i < 10; i++) { funcs.push(function() { alert(i); }); } funcs[0](); //?? 10 Every function has a reference to the same i!

Function calls make fresh variables var funcs = []; for (var i = 0; i < 10; i++) { (function(j) { funcs.push(function() { alert(j); }); }(i)); } funcs[0](); // 0

First-class functions Convenient callbacks Very useful for asynchronous programming. var screen; retrievefromnetwork(function(result) { screen.display(result); });

First-class functions Capabilities Fine-grained access control to objects. counter.next(); counter.reset(); var x = new Collaborator(counter.next); x.dosomething();

First-class functions Functional programming Abstract out behavioral patterns. var x2 = function(x) { return x * 2; } var a = [1, 2, 3]; var b = a.map(x2); // b = [2, 4, 6]

First-class functions Higher-order functions Functions that take, manipulate and return other functions. (Practical example and exercise on the next slides)

Wrap existing methods // Decorate function call with logging. function add_logging(object, member) { var fn = object[member]; } object[member] = function() { alert(member + ' called.'); fn.apply(this, arguments); } add_logging(array.prototype, 'push'); [].push(1); // 'push called.'

Exercise 5 (optional) Memoization Write a higher-order function that makes arbitrary functions more efficient by caching their results.

Binding of this this will only be bound if you call object.method() exactly. An inner function in a method will lose the reference to this!

Binding of this Object.prototype.method = function() { this.x = 0; var inc = function() { this.x++; }; inc(); alert(x); //? }; You ll usually pass inc away as a callback (and it will fail).

Binding of this Object.prototype.method = function() { this.x = 0; var inc = function() { this.x++; }; inc(); alert(x); //? 0 }; You ll usually pass inc away as a callback (and it will fail).

Binding of this Object.prototype.method = function() { this.x = 0; var inc = function() { }; this.x++; }; inc(); alert(x); //? You ll usually pass inc away as a callback (and it will fail). inc() called without object so this got bound to global object. 0

Capture this in closure Object.prototype.method = function() { this.x = 0; var self = this; var inc = function() { self.x++; }; inc(); alert(x); // 1 };

Passing around methods MooTools has bind() method that retains the reference to this: dog.age = 3; dog_birthday = dog.birthday.bind(dog); dog_birthday(); alert(dog.age); // 4 jquery doesn t but we can make it!

bind() function Function.prototype.bind = function(inst) { var fn = this; return function() { fn.apply(inst, arguments); } } Closes over inst, the instance to be applied to, as well as this.

Implicit type conversions false == false // true false == 0 // true '0' == 0 // true '' == false // true '0' == false // true '0' == '' // false If A == B and B == C then A == C doesn t hold! Use === for strict equality checking.

Good Parts Literals for Objects, Arrays, Functions Closures Duck typing Flexible object pattern

Bad parts Global namespace by default Implicit type conversions Semicolon insertion Binding of this

Coffee Break