Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Martin Kruliš by Martin Kruliš (v1.2) 31.10.2016.

Similar presentations


Presentation on theme: "JavaScript Martin Kruliš by Martin Kruliš (v1.2) 31.10.2016."— Presentation transcript:

1 JavaScript Martin Kruliš by Martin Kruliš (v1.2)

2 JavaScript Name Debunking
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 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. by Martin Kruliš (v1.2)

3 JavaScript History First Appearance Standardization At Server Side
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 by Martin Kruliš (v1.2)

4 ECMAScript ECMAScript Scripting Languages Ecma International
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 See for current browser support by Martin Kruliš (v1.2)

5 Language Fundamentals
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: ... } by Martin Kruliš (v1.2)

6 Language Fundamentals
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 Note that 4 + "5" and "5" + 4 * 2 expressions produce also string results ("45" and "58"). by Martin Kruliš (v1.2)

7 Language Fundamentals
Variables Mnemonic holders for values Rather “attachments” to values than “memory boxes” Declared by var keyword var 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) Note that a variable does not have any type, so it can hold to any value. In fact, it is possible to set values of different types into a variable during its lifetime. We sometimes refer to the “type of a variable”, but we actually mean the type of the value currently associated with that variable. These are the beauties and the treacheries of week-typed languages. Handle them with care. by Martin Kruliš (v1.2)

8 Language Fundamentals
Block Scope C++, C#, Java, … if (x < 0) { bool negative = true; } else { bool negative = false; // negative does not exist here … Function Scope JavaScript function foo() { var x = 1; function bar() { var y = 2; // x exists here } // y does not exist here by Martin Kruliš (v1.2)

9 Functions 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 Lambda functions Nested declarations are allowed Most imperative languages treat functions/methods as second-class citizens (second-class functions). It means, that functions are statically defined at compile time, but it is possible to take pointer to a function and call a function indirectly (via pointers or delegates). by Martin Kruliš (v1.2)

10 Functions Function Scope of Variables
var 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; } We follow the scope chain upwards and find the first variable of the name 'a2'. by Martin Kruliš (v1.2)

11 Functions Closure function createAdder(x) { return function(y) {
Example 1 Closure function createAdder(x) { return function(y) { return x + y; } var add3 = createAdder(3); var add7 = createAdder(7); add3(10); // is 13 add7(10); // is 17 The Inner function can see variable x due to scoping rules When the inner function is created, the closure captures value of x == 3 New function have a new closure where x == 7 by Martin Kruliš (v1.2)

12 Functions Closure Pitfalls function createLinks() {
All the links are created in one scope, thus sharing one closure. Closure Pitfalls function 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; Always prints “6”. The value of i is 6, when the scope is closed. by Martin Kruliš (v1.2)

13 Members may be added dynamically.
Objects Objects Objects are unordered name-value collections All members are public var myObject = { foo: 10, bar: function() { ... } }; myObject.bar(); myObject.anotherFoo = 100; 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. by Martin Kruliš (v1.2)

14 What do you mean? No classes?!
Objects What do you mean? No classes?! Wait for ECMA Script 6! Classes There are no classes! But we have prototypes [[Prototype]] foo bar name printName() Object.prototype NamedObject myObject Classes were presented in the next version of the language (ECMAScript 6). More details in the advanced lecture (in summer term). Searches up the prototype chain, looks for the first printName property myObject.printName(); Example 2 by Martin Kruliš (v1.2)

15 Objects Constructors var Circle = function(r) { this.radius = r; };
Constructor looks like an ordinary function Constructors var Circle = function(r) { this.radius = r; }; Circle.prototype.foo = function() { … } var myCircle = new Circle(42); 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 by Martin Kruliš (v1.2)

16 Objects Constructors Example Class-based Language JavaScript Example 3
MyClass .prototype MySubclass myObj [[Prototype]] empty object MyClass obj new Object.prototype Class-based Language JavaScript myObj MySubclass MyClass Example 3 by Martin Kruliš (v1.2)

17 this refers to global environment
Keyword this 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(); Note that in case of: var foo2 = obj.foo; foo2(); The this value in foo2 invocation will refer to script environment, not the obj. this refers to global environment this refers to obj by Martin Kruliš (v1.2)

18 JavaScript Built-ins 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 by Martin Kruliš (v1.2)

19 JavaScript Built-ins 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… by Martin Kruliš (v1.2)

20 Object 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 by Martin Kruliš (v1.2)

21 Array Creating Arrays Accessing Elements
var arr = [ 1, 3, 19, 42 ]; var arr = new Array(1, 3, 19, 42); var arr = new Array(length); Accessing Elements var arr = [ 'x', 'y', 'z' ]; console.log(arr[1]); arr[2] = 'zzz'; arr[arr.length] = 'another one'; delete arr[1]; Prints ‘y’ Adds new item to arr (and increments arr.length) The delete arr[1]; operation removes second item from array, but the indices are not compacted. I.e., the array will have items arr[0] == 'x'; arr[2] == ‘zzz'; arr[3] == ‘another one'; and the arr.length property remains == 4. Removes second item, but maintain indices Note that obj['foo'] is the same as obj.foo by Martin Kruliš (v1.2)

22 Array 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 by Martin Kruliš (v1.2)

23 String 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 by Martin Kruliš (v1.2)

24 Code Evaluation Explicit Evaluation The eval(code) function
The code is JavaScript code represented as string The code is interpreted and its last value is returned eval("3+4"); // returns 7 The eval() should be avoided whenever possible eval("var res = obj." + propName); is equivalent with var res = obj[propName]; Functions as callbacks can be used in many places to avoid explicit eval() call Note that eval() is not considered a good programming practice and it is dedicated for very special cases. However, it is a good example of how dynamic interpret languages are being processed. by Martin Kruliš (v1.2)

25 Errors Errors/Exceptions JavaScript is very error-prone language
Error usually stops current JavaScript code Error handling is similar to exception catching: try { ... secured code ... } catch(err) { ... error handling ... } finally { ... finalization code ... } Can be triggered manually throw something; Regular errors are created by Error constructor Parameter message with human-readable description Multiple catch blocks are allowed: try {} catch(e1 if condition1) { … first handling … } catch(e) { … default handling … } by Martin Kruliš (v1.2)

26 ECMA Script 6 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 by Martin Kruliš (v1.2)

27 Discussion by Martin Kruliš (v1.2)


Download ppt "JavaScript Martin Kruliš by Martin Kruliš (v1.2) 31.10.2016."

Similar presentations


Ads by Google