27
JavaScript Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1) 1

Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

Embed Size (px)

Citation preview

Page 1: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 1

JavaScriptMartin Kruliš

19. 11. 2015

Page 2: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 2

JavaScript◦ Dynamically typed◦ Prototype based◦ Have functions◦ Support closures◦ Function scope◦ Implicit global scope◦ this depends on the

manner of function call◦ Constructing functions◦ All functions are

variadic◦ …

19. 11. 2015

JavaScript Name Debunking

Java◦ Statically typed◦ Class based◦ Have methods◦ Only anonymous

classes◦ Block scope◦ Implicit class scope◦ Exact this keyword in

non-static methods◦ Constructor methods◦ Explicit variadic def.◦ …

Page 3: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 3

First Appearance◦ Developed by Brendan Eich in Netscape as a

scripting language for web browser (early 90’s)◦ Named after Java for marketing reasons◦ Adopted by Microsoft in MSIE 3.0 (1996)

Standardization◦ Language part standardized as ECMAScript (1997)

At Server Side◦ Netscape Enterprise Server (1994)◦ Most recently in Node.js

19. 11. 2015

JavaScript History

Page 4: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 4

ECMAScript◦ Standardizes only the language◦ Version 6 recently standardized (we cover v 5.1)

Not fully implemented in current web browsers yet

Scripting Languages◦ JavaScript – ECMAScript adapted for web browser◦ JScript – Microsoft variation on the JavaScript theme◦ ActionScript – ECMAScript used in Adobe Flash

Ecma International◦ Non-profit standards organization

19. 11. 2015

ECMAScript

Page 5: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 5

Basic Syntax is C-like◦ Expressions

Arithmetic =, +, -, *, /, %, … Comparisons <, >, ==, !=, ===, !==, <=, >=, … Logical &&, ||, !, …

◦ Statements if (cond) stm1; else stm2; while (cond) stm; for (init; cond; inc) stm; for (variable in obj) stm; switch (expr) { case lbl: ... }

19. 11. 2015

Language Fundamentals

Page 6: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 6

Values◦ Any expression or literal produces a value◦ There are following value types: number, string, boolean, object, function, and undefined Operator typeof returns the type of an expression

◦ Values are automatically garbage-collected when no longer needed

◦ Some type conversions are performed automatically "5" + 4 // is "54" (string) "5" * 4 // is 20 (number) console.log(myObject) // .toString() invoked

19. 11. 2015

Language Fundamentals

Page 7: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 7

Variables◦ Mnemonic holders for values

Rather “attachments” to values than “memory boxes”◦ Declared by var keywordvar x; var y = 1; var a, b, c;

◦ The declaration is affected by the current scope In global scope, the variables are assigned to the script

environment (e.g., object window in the browser)var x = 1; (global) and window.x = 1; are equivalent

In a function, the variable belongs to the local scope (more details later)

19. 11. 2015

Language Fundamentals

Page 8: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 8

Block Scope◦ C++, C#, Java, …

if (x < 0) { bool negative = true;}else { bool negative = false;}

// negative does not exist here …

19. 11. 2015

Language Fundamentals Function Scope

◦ JavaScript

function foo() { var x = 1; function bar() { var y = 2; // x exists here } // y does not exist here}

Page 9: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 9

Functions◦ Special “callable” objects (first-class functions)◦ Various ways to create them

function foo(args) { body }var foo = function(args) { body }var foo = new Function(args, "body");

◦ Function declaration = object creation◦ Variadic – implicitly variable arity

Calling arguments are assigned to declared arguments Also present in local array arguments (in the body)

◦ No difference between functions and methods

19. 11. 2015

Functions

• Lambda functions• Nested declarations

are allowed• …

Page 10: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 10

Function Scope of Variablesvar a1; // global scope (obj. window in Browser)function foo() { var a2; // local scope of foo() function innerFoo() { var a3; // local scope of innerFoo() function innerInnerFoo() { // I can see a1, a2, and a3 from here … a2 = 1; } }}

19. 11. 2015

Functions

We follow the scope chain upwards and find the first variable of the name

'a2'.

Page 11: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 11

Closurefunction createAdder(x) { return function(y) { return x + y; }}

var add3 = createAdder(3);var add7 = createAdder(7);

add3(10); // is 13add7(10); // is 17

19. 11. 2015

Functions

When the inner function is created, the closure

captures value of x == 3

New function have a new closure where x ==

7

The Inner function can see variable x due to scoping

rules

Example 1

Page 12: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 12

Closure Pitfallsfunction createLinks() { for (var i = 1; i <= 5; ++i) { var link = document.createElement('a'); link.onclick = function(){ alert(i); }; link.textContent = "Link " + i; document.body.appendChild(link); }}document.onload = createLinks;

19. 11. 2015

FunctionsAll the links are created in one

scope, thus sharing one closure.

The value of i is 6, when the scope is closed.

Always prints “6”.

Page 13: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 13

Objects◦ Objects are unordered name-value collections◦ All members are publicvar myObject = { foo: 10, bar: function() { ... }};myObject.bar();myObject.anotherFoo = 100;

19. 11. 2015

Objects

Creates simple object with two members (foo and bar), where foo

is a Number and bar is Function (i.e., in some sense a method).

Members may be added dynamically.

Page 14: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 14

Classes◦ There are no classes!◦ But we have prototypes

19. 11. 2015

ObjectsWhat do you mean? No classes?!

Wait for ECMA Script 6!

myObject.printName();

[[Prototype]]foobar

[[Prototype]]nameprintName()

Object.prototype

NamedObjectmyObject

Example 2

Searches up the prototype chain, looks for the first printName property

Page 15: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 15

Constructors

var Circle = function(r) { this.radius = r;};

Circle.prototype.foo = function() { … }

var myCircle = new Circle(42);

19. 11. 2015

ObjectsConstructor looks like an ordinary function

this refers to the newly created object (so it can be

initialized)The prototype attribute is set to an empty object

… so it can be easily augmented

Creates new object and copies Circle.prototype to internal [[Prototype]] of the new object

Page 16: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 16

Constructors Example

19. 11. 2015

Objects

Example 3

myObj

MySubclass

MyClass MyClass.prototype

MySubclass.prototype

myObj[[Prototype]]

empty object[[Prototype]]

MyClass obj[[Prototype]]

new

new

Object.prototypeClass-basedLanguage

JavaScript

Page 17: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 17

Keyword this◦ Implicitly declared variable which has different

values in different contexts◦ Global context

this refers to the script environment (e.g., window)◦ Function context

this value depends on how the function was called

foo();

obj.foo();

19. 11. 2015

Keyword this

this refers to global environment

this refers to obj

Page 18: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 18

General-purpose Constructors◦ Wrappers for basic types

Number, String, Boolean, Object, Function Basic primitives (string, boolean, and number) are

automatically converted to their respective wrappers E.g., when a method is invoked upon them

Provide additional functionality◦ Array – object wrapper for “traditional” arrays◦ Date – time and date information◦ Iterator – implements iterator pattern◦ RegExp – regular expression

19. 11. 2015

JavaScript Built-ins

Page 19: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 19

Non-constructor Functions◦ encodeURI(str) – encode string for URI◦ decodeURI(str) – decode URI to normal string◦ parseInt(str, rdx) – parse textual

representation of an integer of given radix◦ parseFloat(str) – parse textual representation

of a floating point number◦ encode(str) – encode non-ascii chars◦ decode(str) – reverse function to encode()◦ eval(str) – to be reviewed later…

19. 11. 2015

JavaScript Built-ins

Page 20: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 20

Constructor Object◦ var o = new Object(value);◦ All objects are descendants of an Object◦ Interesting properties

create(proto, [props]) – create new object getOwnPropertyNames(obj) – return array of

property names that are native to obj getPrototypeOf(obj) – get prototype object of obj preventExtensions(obj) – prevent properties from

being added to obj object seal(obj) – prevent adding/removing properties freeze(obj) – prevent any property modifications

19. 11. 2015

Object

Page 21: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 21

Creating Arraysvar arr = [ 1, 3, 19, 42 ];var arr = new Array(1, 3, 19, 42);var arr = new Array(length);

Accessing Elementsvar arr = [ 'x', 'y', 'z' ];console.log(arr[1]);arr[2] = 'zzz';arr[arr.length] = 'another one';delete arr[1];

19. 11. 2015

Array

Prints ‘y’Adds new item to

arr

Removes second item

Note that obj['foo'] is the same as obj.foo

Page 22: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 22

Methods◦ pop(), push(e1, …) – add/remove end of array◦ shift(), unshift(e1, …) – like pop/push at front◦ slice(begin, end) – get sub-array (range)◦ splice(idx, count, e1, …) – update sub-array◦ sort()◦ join(sep) – glue elements together into a string◦ indexOf(elem) – find element in array◦ forEach(fnc) – invoke a function for each element◦ filter(fnc) – return array filtered by a function◦ map(fnc) – generate elements by a map function

19. 11. 2015

Array

Page 23: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 23

String Methods◦ charAt(idx) – returns one character◦ concat(s1, …) – concatenate strings◦ indexOf(str) – finds a substring within a string◦ match(regexp) – test regular expression match◦ replace(old, new) – replace part of the string◦ slice(from, to) – return a substring◦ split(sep) – chop the string to array of tokens◦ toLowerCase() – return a new lower-cased string◦ trim() – remove leading and trailing whitespace

19. 11. 2015

String

Page 24: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 24

Explicit Evaluation◦ The eval(code) function◦ The code is JavaScript code represented as string◦ The code is interpreted and its last value is

returnedeval("3+4"); // returns 7

◦ The eval() should be omitted whenever possible eval("var res = obj." + propName);

is equivalent withvar res = obj[propName];

Functions as callbacks can be used in many places to avoid explicit eval() call

19. 11. 2015

Code Evaluation

Page 25: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 25

Errors/Exceptions◦ JavaScript is very error-prone language◦ Error usually stops the JavaScript engine◦ Error handling is similar to exception catching:

try { ... secured code ... }catch(err) { ... error handling ... }finally { ... finalization code ... }

◦ Can be triggered manuallythrow something;

◦ Regular errors are created by Error constructor Parameter message with human-readable description

19. 11. 2015

Errors

Page 26: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 26

What is new in ECMA Script 6 (Harmony)◦ Classes◦ Modules◦ Block Scoping – with special syntax (let)◦ Arrow Functions – anonymous functions◦ Default parameter values◦ Destructing assignments◦ Generators◦ Core library extended

Promises, proxies, weakmaps, weaksets, typed arrays

19. 11. 2015

ECMA Script 6

Page 27: Martin Kruliš 19. 11. 2015 by Martin Kruliš (v1.1)1

by Martin Kruliš (v1.1) 2719. 11. 2015

Discussion