Martin Kruliš 11. 4. 2016 by Martin Kruliš (v1.1)1.

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Martin Kruliš This is an Object Oriented system. If we change something, the users object by Martin Kruliš (v1.0)1.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
JavaScript, Fourth Edition
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
1 SystemVerilog Enhancement Requests Daniel Schostak Principal Engineer February 26 th 2010.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
Martin Kruliš by Martin Kruliš (v1.0)1.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Martin Kruliš by Martin Kruliš (v1.0)1.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Object-Oriented Programming Chapter Chapter
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
ISBN Object-Oriented Programming Chapter Chapter
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
OOP Basics Classes & Methods (c) IDMS/SQL News
Martin Kruliš by Martin Kruliš (v1.0)1.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Introduction to Object-oriented Programming
OOP: Encapsulation &Abstraction
Classes C++ representation of an object
Advance OOP in PHP.
Game-Changing Features in ES2015
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
6 Delegate and Lambda Expressions
JavaScript in More Detail
CS5220 Advanced Topics in Web Programming JavaScript Basics
Object-Oriented Programming in PHP
Chapter 8 Class Inheritance and Interfaces
Classes C++ representation of an object
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Modern JavaScript (since ES6 Harmony)
Review for Midterm 3.
JavaScript Internals and OOP Concepts
Presentation transcript:

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

 Closure function make() { var x = 1; return function(dx) { x += dx; alert(x); } } var f1 = make(); var f2 = make(); f1(3); f2(7); 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]]

 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); by Martin Kruliš (v1.1)3 Closure automatically snapshots arguments

 Hiding Encapsulated Functionality ◦ Private functions, related data structures, … var searcher = (function(){ var lookupTable = [... ]; function findPattern(needle) {... } return function(needle, haystack) { var ptrn = findPattern(needle);... } })(); by Martin Kruliš (v1.1)4 Hidden data structure and function The outer function is immediately invoked and then forgotten

 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")); by Martin Kruliš (v1.1)5 Event handler accidentally get hold of parent’s activation object which is not required by the handler

 Naming Collisions in Scope Chain var module = (function(){ var param = 1; function updateParam(param) { param += 1; } return { func: function() { updateParam(param); } }; })(); by Martin Kruliš (v1.1)6 Function argument hides param variable, which was privatized by the scope chain Empty operation (does not modify param )

 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,...); by Martin Kruliš (v1.1)7

 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 by Martin Kruliš (v1.1)8

 Constructors var Circle = function(r) { // initialization this.radius = r; }; Circle.prototype = new GeometricObject(); var myCircle = new Circle(42); 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

 Naïve Approach function MyClass(init) { var privateMember; var privateMethod = function() {... } this.member = init; this.method = function() {... }; } var myObject = new MyClass(42); by Martin Kruliš (v1.1)10 Privacy achieved by closure Methods are created over and over with every instance 

 Naïve Approach function MyClass(init) { var privateMember; function privateMethod() {... } this.member = init; } MyClass.prototype.method = function() {... } var myObject = new MyClass(42); by Martin Kruliš (v1.1)11 Better, since the method is created only once and shared

 Naïve Approach function MyClass(init) { var privateMember; function privateMethod() {... } this.privilegedMethod = function() {}; } MyClass.prototype.publicMethod = function() { … } var myObject = new MyClass(42); by Martin Kruliš (v1.1)12 Privileged method is public, but it can access private members

 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 by Martin Kruliš (v1.1)13

 Simple Inheritance ◦ Using the prototype chain function Person() {... } Person.prototype.registerHobby = function(h)... function Student() {... } Student.prototype = new Person(); Student.prototype.visitCourse = function(c) by Martin Kruliš (v1.1)14 Base “class” Makes Student inherit from Person The prototype object can be augmented

 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, … by Martin Kruliš (v1.1)15

 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; } by Martin Kruliš (v1.1)16 Base “class” this is thrown away and replaced by augmented object of a different class

 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(); by Martin Kruliš (v1.1)17 New lightweight constructor, which uses the same prototype as parent class

 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 by Martin Kruliš (v1.1)18

 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) by Martin Kruliš (v1.1)19

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

 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  … by Martin Kruliš (v1.1)21 Example

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

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

 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; } by Martin Kruliš (v1.1)24

 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% by Martin Kruliš (v1.1)25

 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; } by Martin Kruliš (v1.1)26

 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()); by Martin Kruliš (v1.1)27

 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 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); } );

 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 by Martin Kruliš (v1.1)29

 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 by Martin Kruliš (v1.1)30

 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}) { … } by Martin Kruliš (v1.1)31

 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); by Martin Kruliš (v1.1)32

 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); } }); by Martin Kruliš (v1.1)33

 Promises function ajaxGet(url, timeout, onData, onError) { … } let ajaxPromised = (url, timeout) => { return new Promise((resolve, reject) => { ajaxGet(url, timeout, resolve, reject); }); } Promise.all([ ajaxPromised(" 500), ajaxPromised(" 500), ajaxPromised(" 500), ]).then((data) => { let [ foo, bar, spam ] = data; showData(foo, bar, spam); }, (err) => { alert(err) } ); by Martin Kruliš (v1.1)34

 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 by Martin Kruliš (v1.1)35

by Martin Kruliš (v1.1)36