Introduction to Object Oriented Programming

Introduction to Object Oriented Programming (Hebrew University, CS 67125 / Spring 2012 ) Based on http://moodle.cs.huji.ac.il/cs09/file.php/67555/Lec...
4 downloads 0 Views 393KB Size
Introduction to Object Oriented Programming (Hebrew University, CS 67125 / Spring 2012 )

Based on http://moodle.cs.huji.ac.il/cs09/file.php/67555/Lecture1.pdf @ Ohad Assulin and http://www.w3schools.com/js/default.asp

JavaScript Objects • JavaScript is fundamentally about objects – Arrays & functions are actually objects

• Objects are collections of name-value pairs: – Names are strings – Values are strings, numbers, booleans, and objects (including arrays and functions)

• The members of an object are all public members – Any function can access, modify, or delete those members, or add new members

OOP Lecture 10 @ cs huji 2012

2

Creating a New Object • JavaScript objects are defined dynamically • new Object() – creates a new object on the fly – var messi = new Object();

• Define members on the fly, and give them values – messi.name = “Lionel Messi“; // A new member - name – messi[”nGoals”] = 50; // Another way to declare a new member

• Define methods + implementation on the fly! – Use the function() keyword – messi.play = function() { this.state = “goooooool!" ; // New members defined on the fly, // inside the method this.nGoals++; } OOP Lecture 10 @ cs huji 2012

3

Creating a New Object Alternative var Ronaldo = { name : “Cristiano Ronaldo", // name is a member team : “Real Madrid", // so is team nTitlesIn2012 : 1, // and nTitlesIn2012 play : function() { // play is a method alert(“I am such a good player! I won " + this.nTitlesIn2012 + “ titles this year!” ); } };

• Using the object: – alert(Ronaldo.name) – Ronaldo.play()

OOP Lecture 10 @ cs huji 2012

4

JavaScript Classes • The concept of JavaScript classes is similar to Java classes • As (pretty much) every variable in JS is an object, classes allow us to define a family of object that share common features (members and methods) • JavaScript supplies different classes that were discussed last week – String, Boolean, Number, Math, RegExp, etc. – You can also create and use your own classes OOP Lecture 10 @ cs huji 2012

5

Creating a New Class • Use a constructor to declare a new class function UserClass(parameters) { }

• To create a new object, use the new keyword. var myobject = new UserClass("hi")

• Any JS function can serve as constructor • Just call it using the new keyword

OOP Lecture 10 @ cs huji 2012

6

Creating a New Class • Class declaration can contain members – Use the keyword this function UserClass(parameter){ this.member1 = parameter; this. member2 = “OOPs I did it again" ; }

• Access the members like accessing any other variable var myObject = new UserClass(“My life is perfect") alert(myObject.member1)

OOP Lecture 10 @ cs huji 2012

7

Creating a New Class • Class declaration can also contain methods (“method functions”) a. Define the required function b. Connect it to the class // method function; alerts the player name and the matching team function presentplayer(){ var str = this.name + " plays for " + this.team; return str; } function player(name, team) { this.name = name; this.team = team; this.present = presentplayer; } OOP Lecture 10 @ cs huji 2012

Set members Set methods 8

Creating a New Class • Methods can also be defined internally function player(name, team) { this.name = name; this.team = team; // a function that was defined before, either within the class or outside this.present = presentplayer; // a function that is defined and set here this.present2 = function() { return this.name + " plays for " + this.team; } } // usage Rooney = new player (“Wayne Rooney“, “Man Utd”); //alerts “Wayne Rooney plays for Man Utd” alert(Rooney.present()); Drogba = new player (“Didier Drogba“, “Chelsea”); alert(Drogba.present2()); //alerts “Didier Drogba plays for Chelsea” OOP Lecture 10 @ cs huji 2012

9

Foreach Loop • The for ... in statement goes over the properties of an object for (var property in Drogba){ document.write(property + “: “+ Drogba[property]+”
"); }

• output: name: Didier Drogba team: Chelsea present: function presentplayer() { var str = this.name + (" plays for " + this.team); return str; } present2: function () { return this.name + " plays for " + this.team; }

• class_example.html OOP Lecture 10 @ cs huji 2012

10

Privileges • The members of a class are all public members • Private members are local variables defined by the constructor – Ordinary variables and parameters of the constructor are considered as private members function player(name) { // initialize public properties this.name = name; // private members var secretProperty = 3;

• name, and secretProperty are private • this.name is public

} OOP Lecture 10 @ cs huji 2012

11

Privileges • Private members: – Are not accessible to the outside – Are not accessible to the object's own public methods – Are accessible to private methods • Private methods are inner functions of the constructor

OOP Lecture 10 @ cs huji 2012

12

Privileges – private example • class_private_example.html function player(name) { this.name = name; var secretProperty = 0; // private members function secretFunction() { // private method if (secretProperty < 4) { secretProperty += 1; return true; } else { return false; } } alert(name + " : " + secretFunction() + " : " + secretProperty); } OOP Lecture 10 @ cs huji 2012

13

Prototyping • In JavaScript, you can to add custom properties to objects //adding a custom property to a prebuilt object var bool = new Boolean() // An existing class in JavaScript bool.maybe = 0.5; // adding a custom property to the custom object “player” Drogba = new player ("Didier Drogba", "Chelsea"); Drogba.favoriteColor = “blue";

OOP Lecture 10 @ cs huji 2012

14

Prototyping • A custom property added this way exists only for the specific instance of the class. • Thus, for some other player, Rooney = new player ("Wayne Rooney", "Man Utd");

the “favoriteColor” property doesn’t exist. Rooney.favoriteColor returns by default “undefined”.

OOP Lecture 10 @ cs huji 2012

15

Prototyping • We can also add a property \ method to all the instances of a given class • Use the prototype keyword player.prototype.changeTeam = function(newTeam) { this.team = newTeam; }

• class_prototype_example.html

OOP Lecture 10 @ cs huji 2012

16

Prototyping • Prototyping can be useful in adding new members/methods to existing classes String.prototype.chop = function() { return this.substr(0,this.length-1); } var a = “hello”; var b = a.chop();

• existing_class_prototype_example OOP Lecture 10 @ cs huji 2012

17

Inheritance in JavaScript Object Inheritance • Inheritance in JavaScript is called delegation based inheritance or a prototype based inheritance • Each Javascript object has a prototype member, called __proto__ – This field points to the object’s parent – The prototype may be either an object or the null value – The prototype of an object is an internal property, that exists implicitly – This field only exists in firefox or Chrome (no IE)

OOP Lecture 10 @ cs huji 2012

18

Inheritance in JavaScript Object Inheritance var player = { name: “Messi”, age: 24 };

player prototype player name

Messi

age

24

Properties & methods

_proto_

__proto__ is implicitly defined OOP Lecture 10 @ cs huji 2012

19

Inheritance in JavaScript Object Inheritance var alpha = { num: 10, calculate: function (param) { return this.num * this.yyy * param; } }; Taken from beta or Taken from alpha

gamma

var beta = { yyy: 2, __proto__: alpha }; var gamma = { yyy: 3, __proto__: alpha };

// call the inherited method beta.calculate(4); // 80 gamma.calculate(5); // 150

• object_inheritance_example OOP Lecture 10 @ cs huji 2012

20

Inheritance in JavaScript A prototype chain • Prototype objects are simple objects –  may have their own prototypes – We can concatenate prototypes that have a non-null reference to their prototype

• A prototype chain is a finite chain of objects. This chain enable the usage of inheritance in JavaScript

OOP Lecture 10 @ cs huji 2012

21

Prototype chain • When using a property (or a method), it is first searched at the local context of the objet itself • If it is not found, it is searched in the prototype chain: – If the property is not found in the direct prototype  the prototype of the direct prototype is considered, and so on

• Sound familiar? Like class-based inheritance in Java, when resolving an inherited field \ method • If the property is not found at all, undefined value is returned OOP Lecture 10 @ cs huji 2012

22

Prototype chain • In case a prototype is not specified explicitly, the default value for __proto__ is Object.prototype • Object Object.prototype itself also has a __proto__ that is set to null  This is the final link of a chain alpha

gamma yyy

3

_proto_

num

10

calculate



_proto_

_proto_

beta yyy

Object.prototype

null

2

_proto_ OOP Lecture 10 @ cs huji 2012

23

Inheritance in JavaScript Class Inheritance • In order to perform class inheritance, we need to use the prototype keyword function Alpha() { this.num = 10; this.calculate = function (param) { return this.num * this.yyy * param; } }

function Beta() { this.yyy = 2; } // Beta extends Alpha Beta.prototype = new Alpha(2);

• class_inheritance_example OOP Lecture 10 @ cs huji 2012

24

Exceptions • throw exception; - exception can be any variable (of type integer, boolean or string), or a built-in exception object - No type specification for the errors try { // Some dangerous action } catch (err) { // We are excepting an error object with ‘name’ and ‘message’ properties alert(err.name+", "+err.message); } finally { // statements that are executed regardless of whether an exception is // generated or not in the "try-catch" block } OOP Lecture 10 @ cs huji 2012 25

Exceptions try { // Some dangerous action } catch (errNumber) { // We are excepting an int alert(“error: “+errNumber); }

• But if we think we are expecting an int and in fact we are catching an object? • Too much flexibility can be a problem

• exception_example.html OOP Lecture 10 @ cs huji 2012

26

“Debugging” JavaScript • Firefox error console! – Tools  error-console – Presents a list of errors in the page

Clear after each run

• errors_example.html OOP Lecture 10 @ cs huji 2012

27

“Debugging” – Cont. • Firebug – add-on to Firefox! – https://addons.mozilla.org/en-US/firefox/addon/firebug/

•  enables you to edit, debug, and monitor CSS, HTML, and JavaScript live in any web page • firebug_example.html

OOP Lecture 10 @ cs huji 2012

28

So far0 • Classes • new Object(); / ClassName = { property : “value” , Y } / function ctor(arg1, arg2) {this.var1 = arg1; Y }

• Prototype mechanism • Object inheritance, prototype chain, class inheritance

• Exceptions, Debugging tools • http://www.w3schools.com/js/default.asp • http://www.w3schools.com/jsref/ OOP Lecture 10 @ cs huji 2012

29

Ex4: Sequence Finder & predictor • Input: 1. A query sequence 2. Two lists of subsequences 3. A specific position within the query 4. Scores of the subsequences

• Implementation: JS & HTML only • Should be done aloners

OOP Lecture 10 @ cs huji 2012

30

Ex4: Sequence Finder & predictor • Input: 5. Additional parameters

OOP Lecture 10 @ cs huji 2012

31

Ex4: Sequence Finder & predictor • Output: 1. The query sequence where subsequences are highlighted 2. A report of number of occurrences 3. A score calculated based on the given scores and positions

OOP Lecture 10 @ cs huji 2012

32

Suggest Documents