Presentation is loading. Please wait.

Presentation is loading. Please wait.

Martin Kruliš 11. 11. 2014 by Martin Kruliš (v1.0)1.

Similar presentations


Presentation on theme: "Martin Kruliš 11. 11. 2014 by Martin Kruliš (v1.0)1."— Presentation transcript:

1 Martin Kruliš 11. 11. 2014 by Martin Kruliš (v1.0)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 ◦…◦… 11. 11. 2014 by Martin Kruliš (v1.0)2  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. ◦…◦…

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 11. 11. 2014 by Martin Kruliš (v1.0)3

4  ECMAScript ◦ Standardizes only the language ◦ Current version 5.1 (6 is being prepared)  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 11. 11. 2014 by Martin Kruliš (v1.0)4

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:... } 11. 11. 2014 by Martin Kruliš (v1.0)5

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"  "5" * 4 // is 20  console.log(myObject) //.toString() invoked 11. 11. 2014 by Martin Kruliš (v1.0)6

7  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 made in the current scope  In global scope, the variables are assigned to the script environment (e.g., object window in the browser) var x = 1; and window.x = 1; are equivalent  In a function, the variable belongs to the local scope (more details later) 11. 11. 2014 by Martin Kruliš (v1.0)7

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

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 11. 11. 2014 by Martin Kruliš (v1.0)9 Lambda functions Nested declarations are allowed … Lambda functions Nested declarations are allowed …

10  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; } 11. 11. 2014 by Martin Kruliš (v1.0)10 We follow the scope chain upwards and find the first variable of the name ' a2 '.

11  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 11. 11. 2014 by Martin Kruliš (v1.0)11 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

12  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; 11. 11. 2014 by Martin Kruliš (v1.0)12 All the links are created in one scope, thus sharing one closure. The value of i is 5, when the scope is closed. Always prints “5”.

13  Objects ◦ Objects are unordered name-value collections ◦ All members are public var myObject = { foo: 10, bar: function() {... } }; myObject.bar(); myObject.anotherFoo = 100; 11. 11. 2014 by Martin Kruliš (v1.0)13 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.

14  Classes ◦ There are no classes! ◦ But we have prototypes 11. 11. 2014 by Martin Kruliš (v1.0)14 What do you mean? No classes?! Really. No classes. Sorry! myObject.printName(); [[Prototype]] foo bar [[Prototype]] foo bar [[Prototype]] name printName() [[Prototype]] name printName() Object.prototype NamedObjectmyObject Example 2 Searches up the prototype chain, looks for the first printName property

15  Constructors var Circle = function(r) { this.radius = r; }; Circle.prototype.foo = function() { … } var myCircle = new Circle(42); 11. 11. 2014 by Martin Kruliš (v1.0)15 Constructor 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

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

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(); 11. 11. 2014 by Martin Kruliš (v1.0)17 this refers to global environment this refers to obj

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 11. 11. 2014 by Martin Kruliš (v1.0)18

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… 11. 11. 2014 by Martin Kruliš (v1.0)19

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 11. 11. 2014 by Martin Kruliš (v1.0)20

21  Creating Arrays 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]; 11. 11. 2014 by Martin Kruliš (v1.0)21 Prints ‘y’ Adds new item to arr Removes second item Note that obj['foo'] is the same as obj.foo

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 11. 11. 2014 by Martin Kruliš (v1.0)22

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 11. 11. 2014 by Martin Kruliš (v1.0)23

24  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 omitted 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 11. 11. 2014 by Martin Kruliš (v1.0)24

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 manually throw something; ◦ Regular errors are created by Error constructors  Parameter message with human-readable description 11. 11. 2014 by Martin Kruliš (v1.0)25

26 11. 11. 2014 by Martin Kruliš (v1.0)26


Download ppt "Martin Kruliš 11. 11. 2014 by Martin Kruliš (v1.0)1."

Similar presentations


Ads by Google