Download presentation
Presentation is loading. Please wait.
Published byDonald Collins Modified over 8 years ago
1
Martin Kruliš 11. 4. 2016 by Martin Kruliš (v1.1)1
2
Closure function make() { var x = 1; return function(dx) { x += dx; alert(x); } } var f1 = make(); var f2 = make(); f1(3); f2(7); 11. 4. 2016 by Martin Kruliš (v1.1)2 make() f1() f2() make() f1() f2() global context x = 1 make() act. obj x = 1 make() act. obj dx = 7 f2() act. obj dx = 3 f1() act. obj f1 [[Scope]] f2 [[Scope]] call stack make [[Scope]] 4 4 8 8
3
Binding Function Parameters ◦ Especially useful in case of callbacks function myCallback(data) {... handle callback with data... } function bindArg(fnc, data) { return function() { fnc(data); } myAjax.oncomplete = bindArg(myCallback, reqData); 11. 4. 2016 by Martin Kruliš (v1.1)3 Closure automatically snapshots arguments
4
Hiding Encapsulated Functionality ◦ Private functions, related data structures, … var searcher = (function(){ var lookupTable = [... ]; function findPattern(needle) {... } return function(needle, haystack) { var ptrn = findPattern(needle);... } })(); 11. 4. 2016 by Martin Kruliš (v1.1)4 Hidden data structure and function The outer function is immediately invoked and then forgotten
5
Accidental Closures ◦ Unnecessary closures increases memory footprint function addLinkHandler(link) { if (!link) return; link.onclick = function() { this.href += "?marked=1"; return true; } addLinkHandler(document.getElementById("link1")); 11. 4. 2016 by Martin Kruliš (v1.1)5 Event handler accidentally get hold of parent’s activation object which is not required by the handler
6
Naming Collisions in Scope Chain var module = (function(){ var param = 1; function updateParam(param) { param += 1; } return { func: function() { updateParam(param); } }; })(); 11. 4. 2016 by Martin Kruliš (v1.1)6 Function argument hides param variable, which was privatized by the scope chain Empty operation (does not modify param )
7
Methods (Functions in Object Properties) ◦ this keyword var obj = { x: 1; next: function() { this.x += 1; } }; obj.next(); ◦ Default value is the global context (e.g., window ) ◦ Using/binding different this (and arguments) fnc.apply(this, [args]), fnc.call(this,...) var fnc2 = fnc.bind(this,...); 11. 4. 2016 by Martin Kruliš (v1.1)7
8
Object Oriented Programming ◦ A way to model program components with objects ◦ Comprehensible way to express program parts ◦ Provide some useful concepts Encapsulation, Inheritance, and Polymorphism JavaScript ◦ Gives you objects, closures, and prototype chain ◦ Many ways how to realize traditional OOP None is “the correct one” Use whatever fits your problem 11. 4. 2016 by Martin Kruliš (v1.1)8
9
Constructors var Circle = function(r) { // initialization this.radius = r; }; Circle.prototype = new GeometricObject(); var myCircle = new Circle(42); 11. 4. 2016 by Martin Kruliš (v1.1)9 this refers to the newly created object (geometric object) GeometricObject Circle.prototype Circle.prototype myCircle [[Prototype]] myCircle [[Prototype]] new
10
Naïve Approach function MyClass(init) { var privateMember; var privateMethod = function() {... } this.member = init; this.method = function() {... }; } var myObject = new MyClass(42); 11. 4. 2016 by Martin Kruliš (v1.1)10 Privacy achieved by closure Methods are created over and over with every instance
11
Naïve Approach function MyClass(init) { var privateMember; function privateMethod() {... } this.member = init; } MyClass.prototype.method = function() {... } var myObject = new MyClass(42); 11. 4. 2016 by Martin Kruliš (v1.1)11 Better, since the method is created only once and shared
12
Naïve Approach function MyClass(init) { var privateMember; function privateMethod() {... } this.privilegedMethod = function() {}; } MyClass.prototype.publicMethod = function() { … } var myObject = new MyClass(42); 11. 4. 2016 by Martin Kruliš (v1.1)12 Privileged method is public, but it can access private members
13
Private Members ◦ In the closure created by the constructor invocation ◦ Consider memory footprint of privileged methods ◦ Do you really need private members? Naming convention can achieve similar thing Static Members ◦ ~ members of the constructing function function MyClass() {... } MyClass.staticMember = 42; Virtual Methods ◦ No need – remember how prototype chain works 11. 4. 2016 by Martin Kruliš (v1.1)13
14
Simple Inheritance ◦ Using the prototype chain function Person() {... } Person.prototype.registerHobby = function(h)... function Student() {... } Student.prototype = new Person(); Student.prototype.visitCourse = function(c)... 11. 4. 2016 by Martin Kruliš (v1.1)14 Base “class” Makes Student inherit from Person The prototype object can be augmented
15
Operator instanceof ◦ Whether an object was created by given constructor obj instanceof constructor ◦ Follows the prototype chain (respects inheritance) Instance without inheritance can be tested as Object.getPrototypeOf(o) === constr.prototype Multiple Inheritance ◦ Not directly supported ◦ Can be replaced by Swiss inheritance, traits, mixins, class augmentation, … 11. 4. 2016 by Martin Kruliš (v1.1)15
16
Parasitic Inheritance ◦ Using the prototype chain function Person() {... } Person.prototype.registerHobby = function(h)... function Student() { var that = new Person(); that.visitCourse = function(c)...... return that; } 11. 4. 2016 by Martin Kruliš (v1.1)16 Base “class” this is thrown away and replaced by augmented object of a different class
17
Efficiency Considerations ◦ Problem with simple inheritance SubClass.prototype = new ParentClass(); The parent class may have heavy constructor New parent object is required for each derived class ◦ Possible solution function ParentClass() {... } function SubClass() {... } var tmp = function() {}; tmp.prototype = ParentClass.prototype; SubClass.prototype = new tmp(); 11. 4. 2016 by Martin Kruliš (v1.1)17 New lightweight constructor, which uses the same prototype as parent class
18
Object.prototype.constructor ◦ Reference to a constructor that created the object ◦ Objects inherit constructor from their prototype ◦ Make sure, the constructor is set properly function ParentClass() {... } function SubClass() {... } SubClass.prototype = new ParentClass(); SubClass.prototype.constructor = SubClass; ◦ It may be required when a parent constructor is called by deferred “class”, or for object cloning 11. 4. 2016 by Martin Kruliš (v1.1)18
19
Prototypal Inheritance ◦ Complicated due to constructor indirection ◦ We can create a direct way to link prototypes function createPrototypeOf(o) { function F() {} F.prototype = o; return new F(); } ◦ Modern way in ECMAScript 5 Object.create(proto, params) 11. 4. 2016 by Martin Kruliš (v1.1)19
20
Class Augmentation ◦ Traits, Aggregates, Mixins, Swiss inheritance ◦ Copy (selected) methods (or other members) from one class (prototype) to current class for (var key in aggreg.prototype) { if (!(aggreg.prototype[key] instanceof Function)) continue; if (key in restictedNames) continue; this.prototype[key] = aggreg.prototype[key]; } ◦ You need to deal with overwriting problem 11. 4. 2016 by Martin Kruliš (v1.1)20
21
Creating Classes ◦ Somewhat complicated, many technical details ◦ Most implementations wraps the functionality function createClass(init) {... } Function.prototype.extend = function(init)... ◦ The parameter is an initialization object containing Initial and static values Methods List of mixin/augmentation classes … 11. 4. 2016 by Martin Kruliš (v1.1)21 Example
22
Object Properties ◦ obj.name = value or obj['name'] = value ◦ Object.defineProperty(obj, name, desc) Sets or modifies object property ◦ Descriptor object may contain: configurable – whether the descriptor can be changed enumerable – whether property is visible in keys and for data properties writeable – whether the value can be changed value – initial value of the property and for accessor properties get, set – getter/setter function 11. 4. 2016 by Martin Kruliš (v1.1)22
23
Object Properties ◦ Prevent adding new properties Object.preventExtensions(obj) Object.isExtensible(obj) ◦ Preventing adding or removing properties Object.seal(obj) Object.isSealed(obj) ◦ Preventing any property modifications Object.freeze(obj) Object.isFrozen(obj) 11. 4. 2016 by Martin Kruliš (v1.1)23
24
Making an Object Copy function clone(obj, deep) { if (typeof(obj) != 'object' || obj == null) return obj; // obj is simple value var res = new obj.constructor(); for (var attr in obj) if (obj.hasOwnProperty(attr)) { res[attr] = (deep === true) ? clone(obj[attr], deep) : obj[attr]; } return res; } 11. 4. 2016 by Martin Kruliš (v1.1)24
25
ECMA Script 6 ◦ Finalized in June 2015 Many significant changes But backwards compatible with ES 5 ◦ Current Support Chrome 49, Opera 36 – 90% Firefox 45 – 85 % Edge 13 – 79% MSIE 11 – 15% Safari 9 – 53% Node.js 5.0 – 56% 11. 4. 2016 by Martin Kruliš (v1.1)25
26
Classes ◦ A concept of “real” classes introduced class Circle extends GeometricShape { constructor (x, y, r) { super(x, y); this.r = r; } getArea () { return Math.PI * r * r; } 11. 4. 2016 by Martin Kruliš (v1.1)26
27
Modules ◦ Way to export/import modular values without polluting the global namespace or name collisions // mylib.js export function explain() { return "because 6 x 9"; }; export var universalConst = 42; // an application using mylib.js import * as mylib from "mylib"; console.log(mylib.universalConst + " " + mylib.explain()); // another application using mylib import { explain, universalConst } from "mylib"; console.log(universalConst + " " + explain()); 11. 4. 2016 by Martin Kruliš (v1.1)27
28
Arrow Functions ◦ Simpler syntax for callback functions arr.map(function(x) { return x+1; });// ES 5 arr.map(x => x+1)// ES 6 ◦ Lexical this 11. 4. 2016 by Martin Kruliš (v1.1)28 var self = this; this.values.forEach( function(x){ if (x % 2 != 0) self.odds.push(x); } ); this.values.forEach( (x) => { if (x % 2 != 0) this.odds.push(x); } );
29
Extended Function Parameter Handling ◦ Default parameter values function inc(val, by = 1) { return val + by; } ◦ Aggregation of remaining arguments function merge(al, a2,...restArrays) {} ◦ Spread collection elements as arguments var coords = [ 1, 2,3 ]; point.moveBy(...coords); // moveBy(1, 2, 3); var str = "bar"; var chars = [ "f", "o", "o",...str ]; // b, a, r 11. 4. 2016 by Martin Kruliš (v1.1)29
30
Block Scope ◦ Block scope variables declared by let (instead of var ) for (let i = 0; i < 10; ++i) … ◦ Function declarations are block-scoped as well function foo () { return 1; } foo();// returns 1 { function foo () { return 2; } foo();// returns 2 } foo();// returns 1 11. 4. 2016 by Martin Kruliš (v1.1)30
31
Destructing Assignments ◦ Array matching var list = [ 1, 2, 3 ]; var [ x, y, z ] = list;// var x=1, y=2, z=3 [ z, x, y ] = [ x, y, z ];// rotate values x,y,z ◦ Object matching var { x, y, z } = get3Dpoint(); var { x: x, y: y, attrs: { depth: z } } = get2Dpoint(); ◦ Context argument matching function avgFirst2([a, b]) { return (a + b) / 2; } function distanceTo({x, y, z}) { … } 11. 4. 2016 by Martin Kruliš (v1.1)31
32
Iterators let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1; return { next () { [ pre, cur ] = [ cur, pre + cur ]; return { done:(cur > 1000), value:cur }; } }; } for (let x of fibonacci) console.log(x); 11. 4. 2016 by Martin Kruliš (v1.1)32
33
Proxies let course = { name: "Advanced Technologies for Web Applications", complete: 53,// percent } let proxy = new Proxy(course, { set(target, property, value) { if (property != "complete") return true; return (value >= 0 && value <= 100); } }); 11. 4. 2016 by Martin Kruliš (v1.1)33
34
Promises function ajaxGet(url, timeout, onData, onError) { … } let ajaxPromised = (url, timeout) => { return new Promise((resolve, reject) => { ajaxGet(url, timeout, resolve, reject); }); } Promise.all([ ajaxPromised("http://my.domain/foo.php", 500), ajaxPromised("http://my.domain/bar.php", 500), ajaxPromised("http://my.domain/spam.php", 500), ]).then((data) => { let [ foo, bar, spam ] = data; showData(foo, bar, spam); }, (err) => { alert(err) } ); 11. 4. 2016 by Martin Kruliš (v1.1)34
35
Others ◦ Constants ◦ Template literals ◦ Extended literals (binary, octal, unicode, and regex) ◦ Enhanced regular expressions (sticky matching) ◦ Object properties shorthands ◦ Generators (similar to PHP) ◦ Map and Set data structures ◦ Internalization and localization (collation, formats) ◦ Many new built-in methods 11. 4. 2016 by Martin Kruliš (v1.1)35
36
11. 4. 2016 by Martin Kruliš (v1.1)36
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.