JavaScript Programming

Similar documents
Node.js Training JavaScript. Richard richardrodger.com

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

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

JavaScript Basics. Mendel Rosenblum. CS142 Lecture Notes - JavaScript Basics

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

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

JavaScript. What s wrong with JavaScript?

Ruby: Introduction, Basics

JavaScript. The Bad Parts. Patrick Behr

FALL 2017 CS 498RK JAVASCRIPT. Fashionable and Functional!

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

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

Functional JavaScript. Douglas Crockford Yahoo! Inc.

JavaScript: Sort of a Big Deal,

Course 2320 Supplementary Materials. Modern JavaScript Best Practices

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

ES6 in Practice - The Complete Developer s Guide

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80

IOOR. Lecture 4 Inheritance vs. delegation, Actor-based languages, Methods vs messages, Course council! Prototype-based. Prototype-based PLs

JavaScript CS 4640 Programming Languages for Web Applications

DLint: Dynamically Checking Bad Coding Practices in JavaScript

Chapter 6: Inheritance

JavaScript for PHP Developers

JavaScript: The Good Parts

Principles of Programming Languages

Spring JavaScript. John Mitchell Adapted by Mooly Sagiv. Reading: links on last slide Homework 1: 18/3 17/4

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

Javascript. Daniel Zappala. CS 360 Internet Programming Brigham Young University

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

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

INF5750. Introduction to JavaScript and Node.js

Boot Camp JavaScript Sioux, March 31, 2011

ActionScript Coding Standards. by Michael Williams

JavaScript Lecture 1

Implementing non-static features

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

IAT 355 : Lab 01. Web Basics

Ruby: Objects and Dynamic Types

iwiki Documentation Release 1.0 jch

JavaScript: Features, Trends, and Static Analysis

DLint: Dynamically Checking Bad Coding Practices in JavaScript

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

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Node.js. Mendel Rosenblum. CS142 Lecture Notes - Node.js

CS 142 Final Examination

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

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

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

Lecture 8 (7.5?): Javascript

Variable Declarations

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

Client-Side Web Technologies. JavaScript Part I

Advanced Topics in Programming Languages Spring Semester, Lecture 2: March 13, JavaScript

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

Keyword this. Can be used by any object to refer to itself in any class method Typically used to

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

JavaScript I Language Basics

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

DLint: Dynamically Checking Bad Coding Practices in JavaScript

A Structural Operational Semantics for JavaScript

Ruby: Introduction, Basics

JavaScript: Objects, Methods, Prototypes

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

JavaScript: Coercion, Functions, Arrays

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

JavaScript: the Big Picture

arxiv: v1 [cs.pl] 15 Dec 2009

Notes on JavaScript (aka ECMAScript) and the DOM

JavaScript for C# Programmers Kevin

JavaScript or: How I Learned to Stop Worrying and Love a Classless Loosely Typed Language

Sample CS 142 Midterm Examination

CSC Web Programming. Introduction to JavaScript

Ajax HTML5 Cookies. Sessions 1A and 1B

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

B l o c k B i n d i n g s

Ruby: Introduction, Basics

1B1b Classes in Java Part I

JAVASCRIPT FOR THE C# DEVELOPER

EECS 1001 and EECS 1030M, lab 01 conflict

52 Franck van Breugel and Hamzeh Roumani

Comprehensive AngularJS Programming (5 Days)

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

A general introduction to Functional Programming using Haskell

INTRODUCTION TO JAVASCRIPT

Advanced JavaScript. Advanced JavaScript. Banyan Talks Łukasz Rajchel

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Busy.NET Developer's Guide to ECMAScript

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Developer Entrepreneur Crazy person

Powerful JavaScript OOP concept here and now. CoffeeScript, TypeScript, etc

Advanced Systems Programming

JavaScript Programming

2D Game design Intro to Html 5

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

JavaScript Specialist v2.0 Exam 1D0-735

For this section, we will implement a class with only non-static features, that represents a rectangle

Static Analysis for JavaScript

Transcription:

JavaScript Programming Mendel Rosenblum 1

How do you program in JavaScript? From Wikipedia:... supporting object-oriented, imperative, and functional programming... Mostly programming conventions (i.e. patterns) rather than language features ECMAScript adding language features (e.g. class, =>, etc.) 2

Object-oriented programming: methods A property of an object can be a function var o = {count: 0; o.increment = function (amount) { if (amount == undefined) { amount = 1; this.count += amount; return this.count; Method invocation: o.increment(); // returns 1 o.increment(3); // returns 4 3

this In methods this will be bound to the object var o = {oldprop: 'this is an old property'; o.amethod = function() { this.newprop = "this is a new property"; return Object.keys(this); // will contain 'newprop' o.amethod(); // will return ['oldprop','amethod','newprop'] In non-method functions: this will be the global object Or if "use strict"; this will be undefined 4

functions can have properties too function plus1(value) { if (plus1.invocations == undefined) { plus1.invocations = 0; plus1.invocations++; return value + 1; plus1.invocations will be the number times function is called Acts like static/class properties in object-oriented languages 5

Object-oriented programming: classes Functions are classes in JavaScript: Name the function after the class function Rectangle(width, height) { this.width = width; Not correct way of adding methods this.height = height; this.area = function() { return this.width*this.height; var r = new Rectangle(26, 14); // {width: 26, height: 14 Functions used in this way are called constructors: r.constructor.name == 'Rectangle' console.log(r): Rectangle { width: 26, height: 14, area: [Function] 6

Object-oriented programming: inheritance Javascript has the notion of a prototype object for each object instance Prototype objects can have prototype objects forming a prototype chain On an object property read access JavaScript will search the up the prototype chain until the property is found Effectively the properties of an object are its own property in addition to all the properties up the prototype chain. This is called prototype-based inheritance. Property updates are different: always create property in object if not found Can lead to fun in AngularJS 7

Using prototypes function Rectangle(width, height) { this.width = width; this.height = height; Rectangle.prototype.area = function() { return this.width*this.height; var r = new Rectangle(26, 14); // {width: 26, height: 14 var v = r.area(); // v == 26*14 Object.keys(r) == [ 'width', 'height' ] // own properties Note: Dynamic - changing prototype will cause all instances to change 8

Prototype versus object instances var r = new Rectangle(26, 14); Understand the difference between: And: r.newmethod = function() { console.log('new Method called'); Rectangle.prototype.newMethod = function() { console.log('new Method called'); 9

Inheritance Rectangle.prototype = new Shape(...); If desired property not in Rectangle.prototype then JavaScript will look in Shape.prototype and so on. Can view prototype objects as forming a chain. Lookups go up the prototype chain. Prototype-based inheritance Single inheritance support Can be dynamically created and modified 10

ECMAScript version 6 extensions class Rectangle extends Shape { // Definition and Inheritance constructor(height, width) { this.height = height; this.width = width; area() { // Method definition return this.width * this.height; Static countrects() {... // Static method var r = new Rectangle(10,20); 11

Functional Programming Imperative: for (var i = 0; i < anarr.length; i++) { newarr[i] = anarr[i]*i; Functional: newarr = anarr.map(function (val, ind) { return val*ind; ); Can write entire program as functions with no side-effects anarr.filter(filterfunc).map(mapfunc).reduce(reducefunc); 12

Can mostly but not totally avoid functional style Asynchronous events done with callback functions Browser: function callbackfunc() { console.log("timeout"); settimeout(callbackfunc, 3*1000); Server: function callbackfunc(err, data) { console.log(string(data)); fs.readfile('/etc/passwd', callbackfunc); 13

Closures An advanced programing language concept you need to know about var globalvar = 1; function localfunc(argvar) { var localvar = 0; function embedfunc() {return ++localvar + argvar + globalvar; return embedfunc; var myfunc = localfunc(10); // What happens if a call myfunc()? Again? myfunc closure contains argvar, localvar and globalvar 14

Using Scopes and Closures Consider effect on the scopes of: var i = 1; Versus (function () { var i = 1; )(); 15

Using closures for private object properties var myobj = (function() { var privateprop1 = 1; var privateprop2 = "test"; var setprivate1 = function(val1) { privateprop1 = val1; var compute = function() {return privateprop1 + privateprop2; return {compute: compute, setprivate1: setprivate1; )(); typeof myobj; // 'object' Object.keys(myObj); // [ 'compute', 'setprivate1' ] What does myobj.compute() return? 16

Closures can be tricky with imperative code // Read files './file0' and './file1' and return their length for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); Ends up printing two files to console both starting with: file 2 has length Why? 17

Stepping through the execution for (var fileno = 0; fileno < 2; fileno++) { Execution starts here: fileno= 0 fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); );

Stepping through the execution for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); Call the function fs.readfile, before we can we must evaluate the arguments: the first argument results from the string concatenation operation forming "./file0", the second argument is a function which is passed as a function and its closure containing the variables accessed by the function. In this case only fileno is accessed by the function so the closure contains fileno (which is currently 0).

Stepping through the execution for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); Note that fs.readfile returns after it has started reading the file but before it has called the callback function. The execution does the fileno++ and calls back to fs.readfile with an argument of "./file1" and a new closure and function. The closure has only fileno (which is currently 1).

Stepping through the closure example for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); After creating two function with closures and calling fs.readfile twice the for loop finishes. Some time later in the execution the file reads will finish and fs.readfile will call the functions we passed. Recall that fileno is now 2.

Sometime later: file0 read finishes... for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { './file0' is read so our callback starts executing err if (!err) { is falsy so we go to the console.log statement. console.log('file', fileno, 'has length', data.length); );

Running callbacks... for (var fileno = 0; fileno < 2; fileno++) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); When evaluating the arguments to console.log we go to the closure and look at the current value of fileno. We find it as 2. The result is we print the correct data.length but the wrong file number. The same thing happens for the './fileno1' callback.

Broken fix #1 - Add a local variable for (var fileno = 0; fileno < 2; fileno++) { var localfileno = fileno; fs.readfile('./file' + localfileno, function (err, data) { if (!err) { console.log('file', localfileno,'has length',data.length); ); Closure for callback now contains localfileno. Unfortunately when the callback functions run localfileno will be 1. Better than before since one of the printed lines has the correct fileno.

A fix - Make fileno an argument function printfilelength(fileno) { fs.readfile('./file' + fileno, function (err, data) { if (!err) { console.log('file', fileno, 'has length', data.length); ); for (var fileno = 0; fileno < 2; fileno++) { printfilelength(fileno); Note: This works but sometimes it prints the file0 line first and sometimes it prints the file1 line first.

JavaScript Object Notation (JSON) var obj = { ps: 'str', pn: 1, pa: [1,'two',3,4], po: { sop: 1; var s = JSON.stringify(obj) = '{"ps":"str","pn":1,"pa":[1,"two",3,4],"po":{"sop":1' typeof s == 'string' JSON.parse(s) // returns object with same properties JSON is the standard format for sending data to and from a browser 26

JavaScript: The Bad Parts Declaring variables on use - Workaround: Force declarations var myvar = 2*typeoVar + 1; Automatic semicolon insertion - Workaround: Enforce semicolons with checkers return "This is a long string so I put it on its own line"; Type coercing equals: == - Workaround: Always use ===,!== instead ("" == "0") is false but (0 == "") is true, so is (0 == '0') (false == '0') is true as is (null == undefined) with, eval - Workaround: Don't use 27

Some JavaScript idioms Assign a default value hostname = hostname "localhost"; port = port 80; Access a possible undefined object property var prop = obj && obj.propname; Handling multiple this: fs.readfile(this.filename + fileno, function (err, data) { console.log(this.filename, fileno); // Wrong! ); 28

Some JavaScript idioms Assign a default value hostname = hostname "localhost"; port = port 80; Access a possible undefined object property var prop = obj && obj.propname; Handling multiple this: self var self = this; fs.readfile(self.filename + fileno, function (err, data) { console.log(self.filename,fileno); ); 29