Java Script Martin Kruli by Martin Kruli v
Java. Script Martin Kruliš by Martin Kruliš (v 1. 0) 11. 2014 1
Java. Script Name Debunking � Java. Script 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š (v 1. 0) 11. 2014 2
Java. Script History � 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 by Martin Kruliš (v 1. 0) 11. 2014 3
ECMAScript � ECMAScript ◦ Standardizes only the language ◦ Current version 5. 1 (6 is being prepared) � Scripting Languages ◦ Java. Script – ECMAScript adapted for web browser ◦ JScript – Microsoft variation on the Java. Script theme ◦ Action. Script – ECMAScript used in Adobe Flash � Ecma International ◦ Non-profit standards organization by Martin Kruliš (v 1. 0) 11. 2014 4
Language Fundamentals � Basic Syntax is C-like ◦ Expressions �Arithmetic =, +, -, *, /, %, … �Comparisons <, >, ==, !=, ===, !==, <=, >=, … �Logical &&, ||, !, … ◦ Statements �if (cond) stm 1; else stm 2; �while (cond) stm; �for (init; cond; inc) stm; �for (variable in obj) stm; �switch (expr) { case lbl: . . . } by Martin Kruliš (v 1. 0) 11. 2014 5
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" �"5" * 4 // is 20 �console. log(my. Object) //. to. String() invoked by Martin Kruliš (v 1. 0) 11. 2014 6
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 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) by Martin Kruliš (v 1. 0) 11. 2014 7
Language Fundamentals � Block Scope ◦ C++, C#, Java if (x < 0) { bool negative = true; } else { bool negative = false; } // negative does not exist here … � Function Scope ◦ Java. Script function foo() { var x = 1; function bar() { var y = 2; // x exists here } // y does not exist here } by Martin Kruliš (v 1. 0) 11. 2014 8
Functions � Functions ◦ Special “callable” objects (first-class functions) ◦ Various ways to create them • Lambda functions • Nested declarations function foo(args) { body } var foo = function(args) { body }are allowed • … 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 by Martin Kruliš (v 1. 0) 11. 2014 9
Functions � Function Scope of Variables var a 1; // global scope (obj. window in Browser) function foo() { var a 2; // local scope of foo() function inner. Foo() { var a 3; // local scope of inner. Foo() function inner. Inner. Foo() { // I can see a 1, a 2, and a 3 from here … a 2 = 1; } } We follow the scope chain upwards and } find the first variable of the name 'a 2'. by Martin Kruliš (v 1. 0) 11. 2014 10
Functions � Closure Example 1 function create. Adder(x) { return function(y) { return x + y; } } var add 3 = create. Adder(3); var add 7 = create. Adder(7); add 3(10); add 7(10); // is 13 // 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š (v 1. 0) 11. 2014 11
Functions � Closure Pitfalls All the links are created in one scope, thus sharing one closure. function create. Links() { for (var i = 1; i <= 5; ++i) { var link = document. create. Element('a'); link. onclick = function(){ alert(i); Always prints “ 5”. }; link. text. Content = "Link " + i; document. body. append. Child(link); } The value of i is 5, when the scope is closed. } document. onload = create. Links; by Martin Kruliš (v 1. 0) 11. 2014 12
Objects � Objects ◦ Objects are unordered name-value collections ◦ All members are public var my. Object = { Creates simple object with two members (foo and bar), where foo: 10, is a Number and bar is Function bar: function() { (i. e. , in some sense a method). . } Members may be added }; dynamically. my. Object. bar(); my. Object. another. Foo = 100; by Martin Kruliš (v 1. 0) 11. 2014 13
Objects What do you mean? No classes? ! � Classes ◦ There are no classes! ◦ But we have prototypes Really. No classes. Sorry! my. Object Named. Object [[Prototype]] foo bar [[Prototype]] name print. Name() my. Object. print. Name(); Object. prototype Searches up the prototype chain, looks for the first print. Name property Example 2 by Martin Kruliš (v 1. 0) 11. 2014 14
Objects � Constructors Constructor looks like an ordinary function var Circle = function(r) { this. radius = r; this refers to the newly created object (so it can be initialized) }; The prototype attribute is set to an empty object Circle. prototype. foo = function() { … } … so it can be easily augmented var my. Circle = new Circle(42); Creates new object and copies Circle. prototype to internal [[Prototype]] of the new object by Martin Kruliš (v 1. 0) 11. 2014 15
Objects � Constructors Class-based Language My. Class My. Subclass Example Object. prototype Java. Script empty object My. Class. prototype [[Prototype]] ne w My. Class obj My. Subclass [[Prototype]] . prototype ne w my. Obj [[Prototype]] Example 3 by Martin Kruliš (v 1. 0) 11. 2014 16
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(); this refers to global environment this refers to obj by Martin Kruliš (v 1. 0) 11. 2014 17
Java. Script 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 Reg. Exp – regular expression by Martin Kruliš (v 1. 0) 11. 2014 18
Java. Script Built-ins � Non-constructor Functions ◦ encode. URI(str) – encode string for URI ◦ decode. URI(str) – decode URI to normal string ◦ parse. Int(str, rdx) – parse textual representation of an integer of given radix ◦ parse. Float(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š (v 1. 0) 11. 2014 19
Object � Constructor Object ◦ var o = new Object(value); ◦ All objects are descendants of an Object ◦ Interesting properties �create(proto, [props]) – create new object �get. Own. Property. Names(obj) – return array of property names that are native to obj �get. Prototype. Of(obj) – get prototype object of obj �prevent. Extensions(obj) – prevent properties from being added to object �seal(obj) – prevent adding/removing properties �freeze(obj) – prevent any property modifications by Martin Kruliš (v 1. 0) 11. 2014 20
Array � 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' ]; Prints ‘y’ console. log(arr[1]); Adds new item to arr[2] = 'zzz'; arr[arr. length] = 'another one'; delete arr[1]; Removes second item Note that obj['foo'] is the same as obj. foo by Martin Kruliš (v 1. 0) 11. 2014 21
Array � Methods ◦ ◦ ◦ ◦ ◦ pop(), push(e 1, …) – add/remove end of array shift(), unshift(e 1, …) – like pop/push at front slice(begin, end) – get sub-array (range) splice(idx, count, e 1, …) – update sub-array sort() join(sep) – glue elements together into a string index. Of(elem) – find element in array for. Each(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š (v 1. 0) 11. 2014 22
String � String ◦ ◦ ◦ ◦ ◦ Methods char. At(idx) – returns one character concat(s 1, …) – concatenate strings index. Of(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 to. Lower. Case() – return a new lower-cased string trim() – remove leading and trailing whitespace by Martin Kruliš (v 1. 0) 11. 2014 23
Code Evaluation � Explicit Evaluation ◦ The eval(code) function ◦ The code is Java. Script 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. " + prop. Name); is equivalent with var res = obj[prop. Name]; �Functions as callbacks can be used in many places to avoid explicit eval() call by Martin Kruliš (v 1. 0) 11. 2014 24
Errors � Errors/Exceptions ◦ Java. Script is very error-prone language ◦ Error usually stops the Java. Script 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 by Martin Kruliš (v 1. 0) 11. 2014 25
Discussion by Martin Kruliš (v 1. 0) 11. 2014 26
- Slides: 26