• Keine Ergebnisse gefunden

Modern JavaScript

N/A
N/A
Protected

Academic year: 2022

Aktie "Modern JavaScript"

Copied!
93
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)Modern JavaScript. Baumgartner - @ddprrt - Nov 2020.

(2) Brendan Eich.

(3) JS had to “look like Java” only less so, be Java’s dumb kid brother or boyhostage sidekick..

(4) Plus, I had to be done in ten days or something worse than JS would have happened..

(5) Java Syntax. Self. Prototype inheritance. Perl. Strings, Arrays, Regular Expressions. Scheme Closures. HyperTalk Event Handlers. AWK functions.

(6) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences.

(7) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. var person = { name: "Stefan", age: 38 }.

(8) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. function greet(name) { alert("Hello " + name) } function stefanize(funcs) { funcs("Stefan") } stefanize(greet).

(9) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. function greet(name) { return function(greeting) { alert(greeting + ", " + name) } } greet("Stefan")("Salut").

(10) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. var lifeform = { greet: function() { alert("Hello, " + this.name) }, species: function() { alert("I am a " + this.species) } } function Person(name) { this.name = name this.species = "Human" } function Dog(name, kind) { this.name = name this.species = "Dog" this.kind = kind }. Person.prototype = lifeform Dog.prototype = lifeform var stefan = new Person("Stefan") stefan.greet() var waldi = new Dog( “Waldi”, “Dackel” ) waldi.greet().

(11) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences.

(12) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. !// types as objects var message = new String("Hello").

(13) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. !// types as objects var message = new String("Hello") !// And the Y2K bug in Date.

(14) Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences. !// types as objects var message = new String("Hello") !// And the Y2K bug in Date.

(15) JavaScript is what comes after C if C++ never happened Stefan Baumgartner.

(16) JavaScript is Lisp in C’s clothing. Bryan Cantrill.

(17) 1995. JavaScript’s inception.

(18) 1996. 1995. Introduction of JScript.

(19) 1996. 1995. 1997. ECMAScript Standardization.

(20) 1999. 1996. 1995. 1997. ECMAScript 3 RegEx, better String handling try/catch, etc..

(21) 1999. 1996. 1995. 1997. 2003. ECMAScript 4 abandoned Classes, interfaces, types, ….

(22) 1999. 1996. 1995. 1997. 2009. 2003. ECMAScript 5 “strict” mode, property descriptors JSON, …..

(23) 1999. 1996. 1995. 1997. 2009. 2003.

(24) 1999. 1996. 1995. 1997. 2009. 2003. 2015 ECMAScript 6 / ES2015 Classes, modules, better for loops Destructuring, Promises, Arrow functions Generators ….

(25) 1999. 1996. 1995. 1997. 2009. 2003. 2015.

(26) 1999. 1996. 1995. 1997. 2016 2017 2018. 2009. 2003. 2015.

(27) https://www.ecma-international.org/activities/Languages/Language%20overview.pdf.

(28)

(29) Modern JavaScript in Action.

(30) Block scope assignments !// ES5 var x = 0. !// ES6+ let x = 0. if(someCondition) { var x = 1 }. if(someCondition) { let x = 1 }. console.log(x) !// x !== 1. console.log(x) !// x !== 0.

(31) Const assignments const x = "Stefan" x = 2. const person = { name: "Stefan" }. !// Uncaught TypeError: !// Assignment to constant variable.. person.age = 38 person.name = "Not Stefan". const assignments are block scoped const assignments are immutable reference assignments Objects, Arrays, Sets can still be mutated.

(32) Destructuring const position = [10, 20] const x = position[0] const y = position[1] !// Destructuring! const [x, y] = position const [a, b, !!...rest] = [1, 2, 3, 4, 5]; !// rest operator !!... console.log(a); !// 1 console.log(b); !// 2 console.log(rest); !// [3, 4, 5].

(33) Destructuring function getPosition() { return { x: 50, y: 200, z: 13 }; } const { x, y } = getPosition(); !// renames const { z : zIndex } = getPosition(); !// defaults const { a = 0 } = getPosition();.

(34) Object creation !// ES5 var name = "Stefan"; var age = 38; var person = { name: name, age: age, whoami: function() { return "I am " + this.name + " and I am " + this.age + "years old" } }.

(35) Object creation !// ES6+ const name = "Stefan"; const age = 38; const person = { name, age, whoami() { !// String template literals return `I am ${this.name} and I am ${this.age} years old` } }. Template literals can have any expression within ${} and are multiline.

(36) for loops for (let value of myArray) { !// !!... } for (let index of myArray.keys()) { !// !!... } for (let [index, value] of myArray.entries()) { !// !!... } for (let key in myObject) { }.

(37) Functions !// Default parameters function setVAT(price, vat = 0.2) { return price * (1 + vat) } !// Destructuring function printPerson({ name, age }) { !//!!... } !// Rest arguments function recursivePrint(el, !!...rest) { console.log(el); recursivePrint(rest) } recursivePrint(1, 2, 3, 4, 5, 6).

(38) Arrow functions const shout = (name) !=> name.toUpperCase(). Arrow functions are strictly anonymous Adding a block { } after the arrow requires a return statement Wrap objects in parens to return them immediately Arrow functions are lexical scoped: this is either module scope, class scope, or last function scope.

(39) Spread operator !// passing arguments as list fn(1, 2, 3) !// as array fn(!!...[1, 2, 3]) !// concatenation !// z !== [1, 2, 3, 4, 5, 6, 7] const z = [1, 2, !!...[3, 4, 5], 6, 7] !// cast lists to arrays const imgs = [!!...document.querySelectorAll("img")] !// merge Objects const person = { !!...nameAndAge, !!...personFunctions }.

(40) Classes !// ES5 function Car () { this.fuel = 0; this.distance = 0; } Car.prototype.move = function () { this.fuel!--; this.distance += 2; } Car.prototype.addFuel = function () { this.fuel!++ }. !// ES6+ class Car { constructor () { this.fuel = 0 this.distance = 0 } move () { this.fuel!--; this.distance += 2; } addFuel () { this.fuel!++; } }.

(41) Notes on classes Classes are - Syntactic sugar for prototype / constructor function Object generation - A more convenient way to add getters, setters, and private properties - A more convenient way to add to the prototype chain via extends Classes are not - A type - An abstraction - Java.

(42) Things left out - Maps, Sets, WeakMaps, WeakSets - New functions in Array, Object, Number, String - Reflection, Proxies, generator functions - Symbols and Iterators - ECMAScript modules - async / await and Promises (we might do that in live coding…).

(43) Wrapping up - JavaScript is not a toy language anymore —> powerful constructs! - ECMAScript standards are released once per year - Objects and functions are still at the heart of JavaScript, it just gets more conventient - Convenience functions are idiomatic —> use them.

(44) TypeScript. Baumgartner - @ddprrt - Nov 2020.

(45) 1100001010100011 49827. -15709. £. ….

(46) What is a type?.

(47) A type is a classification of data that defines the operations that can be done on that data, the meaning of the data, and the set of allowed values. Vlad Riscutia.

(48) Typing is checked by the compiler and/or run time to ensure the integrity of the data, enforce access restrictions, and interpret the data as meant by the developer. Vlad Riscutia.

(49) Does JavaScript have types.

(50) http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf.

(51) Type Hierarchy in JavaScript. https://exploringjs.com/impatient-js/ch_values.html.

(52) Type Hierarchy in TypeScript.

(53) TypeScript is a superset of JavaScript TS. JS.

(54) 1999. 1996. 1995. 1997. 2009. 2003. 2016 2017 2018. 2015. ECMAScript 6 / ES2015.

(55) 1999. 1996. 1995. 1997. 2016 2017 2018. 2009. 2003. 2011. TypeScript’s inception. 2015. ECMAScript 6 / ES2015.

(56) Anders Hejlsberg.

(57)

(58)

(59) https://channel9.msdn.com/Shows/Going+Deep/Anders-Hejlsberg-and-Lars-Bak-TypeScript-JavaScript-and-Dart.

(60) TypeScript is JavaScript!.

(61) ⭐ Open Source and Open Development " Closely track ECMAScript standard # Innovate in type system $ Best of breed tooling ⏬ Continually lower barrier to entry & Community, community, community.

(62) ⭐ TypeScript IS JavaScript ⭐ Language innovation through ECMAScript ⭐ Type system innovation through use cases ⭐ Tooling as prime citizen Non-goal: Apply a sound or "provably correct" type system. Instead, strike a balance between correctness and productivity..

(63) ⛩ Gradual, structural, generic ( Distinct value / type namespaces ) Extensive type inference * Control flow analysis & Object-oriented and functional.

(64) Gradual typing.

(65) function addVAT(price, vat) { return price * (1 + vat) // Oh! You add and multiply with numbers, so it's a number } addVAT2(2, 0.2).toUpperCase() // Immediate Krawutzikaputzi function addVAT(price, vat = 0.2) { // great, `vat`is also number! return price * (1 + vat) } /** * Adds VAT to a price * * @param {number} price The price without VAT * @param {number} vat The VAT [0-1] * * @returns {number} */ function addVAT(price, vat = 0.2) { return price * (1 + vat) }.

(66) /** * @typedef {Object} Article * @property {number} price * @property {number} vat * @property {string} string * @property {boolean=} sold */ /** * Now we can use Article as a proper type * @param {[Article]} articles */ function totalAmount(articles) { return articles.reduce((total, article) => { return total + addVAT(article) }, 0) }.

(67) function addVAT(price: number, vat: number): number { return price * (1 + vat) } // or: declare, don’t implement (aka Header file, file comes from a different lib) declare function addVAT(price: number, vat: number): number;.

(68) const defaultOrder = { articles: [ { price: 1200.50, vat: 20, title: 'Macboox Air Refurbished - 2013' }, { price: 9, vat: 0, title: 'I feel smashing subscription' } ], customer: { name: 'Fritz Furball', address: 'Smashing Hill, 90210', dateOfBirth: new Date(2006, 9, 1) } }. This object would make a good type. type Order = typeof defaultOrder;. typeof creates types on the fly. function checkOrders(orders: Order[]) { return orders.reduce((valid, order) => { return valid && order.articles.length > 0 }, true) }.

(69) What’s const in JS?.

(70) const gift = { price: 0, vat: 0, title: 'A bottle opener', } as const; // gift.price = 100; // this breaks. const context makes true const objects.

(71) Structural vs nominal typing.

(72) Duck Typing.

(73) interface Named { name: string; } class Person { name: string; } let p: Named; // OK, because of structural typing p = new Person();. interface Named { name: string; } let x: Named; // y's inferred type is { name: string; location: string; } let y = { name: "Alice", location: "Seattle" }; x = y;.

(74) Type namespaces.

(75) primitive types number Symbol boolean. Object undefined null. string.

(76) top types. any unknown number Symbol. boolean. Object undefined null. string.

(77) bottom types. never. number Symbol boolean. Object undefined null. string.

(78) primitive types number Symbol boolean. Object undefined null. string.

(79) primitive types number. boolean. undefined null. string.

(80) number. value types. …. -1 boolean. NaN. 1000000 6 120.3. true false. string …. undefined null. ‘Hello world’ ‘Baumi’.

(81) value types …. -1. NaN. 1000000 6 120.3. true false … undefined null. ‘Hello world’ ‘Baumi’.

(82) number. value types. …. -1 boolean. NaN. 1000000 6 120.3. true false. string …. undefined null. ‘Hello world’ ‘Baumi’.

(83) number. number | string | undefined. …. -1 boolean. NaN. 1000000 6 120.3. true false. string …. undefined null. ‘Hello world’ ‘Baumi’.

(84) Intersection types. { a: string }. {. }. { b: string } a: string, b: string.

(85) type Talk = { speaker: string, title: string, abstract: string } type TechEvent = { title: string, description: string date: Date, capacity: number, rsvp: number } We want to create Tech events that are tech events, but a little bit more. type Meetup = TechEvent & { type: 'meetup' location: string, price: 'free', talks: Talk[] } type Conference = TechEvent & { type: 'conference', location: string, price: number, talks: Talk[] } type Webinar = TechEvent & { type: 'webinar', url: string, videoUrl: string, talks: Talk }. Intersection types! type TechEvents = Webinar | Conference | Meetup; Union types!.

(86) Generics.

(87) declare class Widget { toJSON(): { kind: "Widget", date: Date } } type Item = { text: string; count: number; choice: "yes" | "no" | null; func: () => void; nested: { isSaved: boolean; data: [1, undefined, 2]; } widget: Widget; children: Item[]; } declare let item: JSONified<Item>;. type JSONified<T> = JSONifiedValue<T extends { toJSON(): infer U } ? U : T>; type JSONifiedValue<T> = T extends string | number | boolean | null ? T : T extends Function ? undefined : T extends Array<infer U> ? JSONifiedArray<U> : T extends object ? JSONifiedObject<T> : undefined; type UndefinedAsNull<T> = T extends undefined ? null : T; interface JSONifiedArray<T> extends Array<UndefinedAsNull<JSONified<T>>> {} type JSONifiedObject<T> = { [P in keyof T]: JSONified<T[P]> }.

(88) type AllElements = { 'a': HTMLAnchorElement; 'div': HTMLDivElement; 'span': HTMLSpanElement; 'ul': HTMLUListElement; 'title': HTMLTitleElement; 'textarea': HTMLTextAreaElement; 'template': HTMLTemplateElement; 'tfoot': HTMLTableSectionElement; 'thead': HTMLTableSectionElement; 'tbody': HTMLTableSectionElement; 'tr': HTMLTableRowElement; 'table': HTMLTableElement; 'col': HTMLTableColElement; 'colgroup': HTMLTableColElement; 'th': HTMLTableHeaderCellElement; 'td': HTMLTableDataCellElement; 'caption': HTMLTableCaptionElement; 'style': HTMLStyleElement; 'select': HTMLSelectElement; 'script': HTMLScriptElement; 'blockquote': HTMLQuoteElement; 'q': HTMLQuoteElement; } Map types. type JSXHTMLElement<T extends keyof AllElements> = AllElements[T]; type JSXElement<T extends string> = T extends keyof AllElements ? JSXHTMLElement<T> : HTMLElement;. Mapped types Conditional types.

(89) Control flow analysis.

(90) function shouting(param: any) { if(typeof param === 'string') { // i am a string return param.toUpperCase() } else if(typeof param === 'number') { // i am a number return `${param}`.toUpperCase() } return 'I HAVE NO IDEA WHAT TO DO' }.

(91) And classes….

(92) class Vendor { name: string;. Which parts are JS, which are TS?. constructor(name: string) { this.name = name; } greet() { return "Hello, welcome to " + this.name; } }. class FoodTruck extends Vendor { cuisine: string; constructor(name: string, cuisine: string) { super(name); this.cuisine = cuisine; } greet() { return "Hi, welcome to food truck " + this.name + ". We serve " + this.cuisine + " food."; } }.

(93) ✅ Gradual, structural, generic ✅ Distinct value / type namespaces ✅ Extensive type inference ✅ Control flow analysis ✅ Object-oriented and functional.

(94)

Referenzen

ÄHNLICHE DOKUMENTE

Dynamic Programming Algorithm Edit Distance Variants..

Edit distance between two strings: the minimum number of edit operations that transforms one string into the another. Dynamic programming algorithm with O (mn) time and O (m)

Dynamic Programming Algorithm Edit Distance Variants.. Augsten (Univ. Salzburg) Similarity Search WS 2019/20 2

[r]

We give a formula for the crystal structure on the integer points of the string polytopes and the ∗-crystal structure on the integer points of the string cones of type A for

Angenommen der binäre Suchbaum ist stark (d.h. maximal) entartet, auf welche Anzahl (minimal, maximal,.. durchschnittlich) von Vergleichen ändert sich

NOTE AC:14, 18 stand for the open vowels (front and back respectively) specifically marked in Marathi orthography and to some extent in Hindi orthography.. NOTE AD: 42 stands for

E ine nachhaltige Herstellung von Treibstoffen und von Grund- stoffen für die chemische Industrie erfordert Prozesse, die ohne fossile Rohstoffe wie Erdöl auskommen. Verfahren,