Java Script Objects and Object Oriented Programming OOP
Java. Script Objects and Object. Oriented Programming (OOP)
2 Java. Script & OOP • Java. Script is object-oriented – even if you don’t realize it – there is a “global object” • all global variables and functions are its properties – there are predefined JS objects – you can add variables and functions to an object's "prototype" (aka class) – you can – and should define your own objects
3 Java. Script Objects • Objects have – a type • the type has a name – attributes • properties – behaviors • functions • in Java. Script, functions are properties, too!
4 Object-Oriented Design • Uses software models that define objects similar to the realworld objects in the problem domain • Models communication between objects • Uses classes for objects that have the same characteristics • Uses inheritance to derive a new classes of objects from existing classes by adding their own unique characteristics • Encapsulates attributes and behaviors of objects by restricting their visibility to outside objects • Allows to redefine the behaviors of derived objects polymorphism • OOP is a natural and intuitive way to view software design
5 Procedural vs. OOP • Procedural programmers concentrate on writing functions – actions that perform a task are composed within functions – a set of functions forms a program • Object-oriented programmers concentrate on creating classes of objects – a class contains data and functions that provide services to clients – a set of classes forms a program
6 Advantages of OOP • A class is to its objects as cookie-cutter is to cookies • OOP make you think in categories • OOP make you tackle large problems in terms of smaller sub-problems • Classes make it possible to reuse them in other projects • With OOP, you can build much of new software by combining existing classes
7 Standard Objects: Math • Math defines methods for most common mathematical calculations – the methods are very similar to those in Java • java. lang. Math – constants • PI, E, LN 2, LN 10, SQRT 2, SQRT 1_2, LOG 2 E, LOG 10 E – methods • • sqrt(x), exp(x), log(x), pow(x, y) sin(x), cos(x), tan(x), atan(x) ceil(x), floor(x), round(x), max(x, y), min(x, y) all these methods are static, i. e. they are called using Math. prefix – e. g. , var x. To. Yth = Math. pow(x, y);
8 Standard Objects: String • Characters as in Java – letters, digits, special characters – Unicode characters – same notation • n, t, f, c, ", ', \ • A string is a series of characters – constants • can be enclosed either in "" or in '' – can be created from Unicode characters using from. Char. Code() • e. g. , String. from. Char. Code(65, 66, 67, 68) creates "ABCD" – concatenation operator + • any type concatenated with a string will be converted to a string • using its to. String() method – property length • holds the number of characters in the string – strings can be compared with ==, !=, <, >, <=, >= • watch out: "aaa" > "ZZZ" because of Unicode ordering (superset of ASCII)
9 String Methods • char. At(index) – returns the character at index – Indices start at 0 and go to length-1 – returns an empty string if index >= length • char. Code. At(index) – returns the Unicode value of the character at index – returns Na. N if index>= length • to. Lower. Case(), to. Upper. Case() – returns the lowercase resp. uppercase version of this string • to. Locale. Lower. Case() to. Locale. Upper. Case() – returns the uppercase lowercase resp. version of this string according to current locale • • index. Of(pattern[, start. Index]) – returns the beginning index of the first occurrence of pattern – returns -1 if pattern is not found – starts search at start. Index if it is given last. Index. Of(pattern[, start. Index]) – returns the beginning index of the last occurrence of pattern – returns -1 if pattern is not found – starts search at start. Index if it is given
10 String Methods (cont. ) • concat(string 2[, . . . , string. N]) – appends string 2 to string. N after this string and returns the concatenated string – this string remains unchanged • split(pattern) – – • breaks this string into token strings delimited by pattern returns an array of the tokens the delimiting pattern is not part of the tokens this string remains unchanged replace(pattern, string 2) – returns a string where the pattern within this string has been replaced by string 2 – this string remains unchanged • locale. Compare(string 2) – returns 1 if this string > string 2, -1 if this string < string 2, and 0 if the strings are equal – uses locale-specific ordering (e. g. , "aaa" < "ZZZ")
11 String Substring Methods • substring(from[, to]) – – • substr(from[, n]) – – • returns the substring of this string starting at from index up to (not including) to index ends the string returned at length-1 if to >= length returns "" if from >= length if to isn't given returns the substring all the way till the end returns the substring of this string starting at from index up to (not including) from+n index ends the returned string at length-1 if to >= length returns "" if from >= length if n isn't given returns the substring all the way till the end slice(from, to) – returns the substring starting at from index up to (not including) to index – same as substring(from, to)
12 String Reg. Exp Methods • search(regexp) – returns the index of the first occurrence of the pattern matching the of regular expression regexp within this string 2 – returns -1 if the pattern doesn't occur in this string – same as index. Of(pattern), except that it uses a regular expression • replace(regexp, string 2) – returns a string where the occurrence of the pattern matching the of regular expression regexp within this string has been replaced by string 2 – if regexp uses the global modifier /…/g then all occurrences will be replaced – this string remains unchanged • match(regexp) – matches pattern(s) of regular expression regexp within this string – returns an array with matched substrings (see later when we discuss regular expressions)
13 String Wrapper Methods • Don't use these, use CSS instead – – – – link(url) • returns this string wrapped into <a href="url"></a> anchor(anchor) • returns this string wrapped into <a name="anchor"></a> bold() • returns this string wrapped into <b</b> italics() • returns this string wrapped into <i></i> fixed() • returns this string wrapped into <tt></tt> blink() • returns this string wrapped into <blink></blink> strike() • returns this string wrapped into <strike></strike> sub() • returns this string wrapped into <sub></sub> sup() • returns this string wrapped into <sup></sup> big() • returns this string wrapped into <big></big> small() • returns this string wrapped into <small></small> fontcolor(color) • returns this string wrapped into <font color="color"><font> fontsize(size) • returns this string wrapped into <font size="size"><font>
14 Object Number • Constants – MAX_VALUE, MIN_VALUE, Na. N – NEGATIVE_INFINITY, POSITIVE_INFINITY • special values representing returned on overflow – Used as static members, e. g. , Number. MAX_VALUE • Only inherited methods – to. String() • Used automatically in string concatenation or when conversion is needed • e. g. , var number = 6; alert(number);
15 Object Boolean • Wrapper for boolean values • Don't use, it only creates confusion! – e. g. , var is. False = new Boolean (false); if (is. False) {alert("is. False is true") } else {alert("is. False is false")} – will output • is. False is true!! • because is. False is an object • and an object within a condition corresponds to true
16 Object Date • • • Represents a date with time Used for current time/date and date/time calculations Several constructors – new Date() • creates object with current date and time according to local time (zone) – new Date(datestring) • creates object with given date (and time) – new Date(year, month, day) • creates object with given date – new Date(year, month, day, hour, minute, secs, msecs) • creates object with given date and time – new Date(msecs. Since 1970) • creates object with time in milliseconds after 1/1/1970 00: 00 UTC/GMT • Static method Date. now() – returns number of milliseconds since 1/1/1970 00: 00 UTC/GMT • non-standard
17 Date Accessor Methods • get. Date(), set. Date(day) • – returns resp. sets the day of the month according to local time get. Day(), set. Day(day), • • – returns resp. sets the day of the week according to local time get. Full. Year(), get. Month(), get. Hours(), get. Minutes(), get. Seconds(), get. Milliseconds() – returns the year, month, hour, minute, second, and millisecond according to local time set. Full. Year(year), set. Month(month), set. Hours(hour), set. Minutes(minute), set. Seconds(sec), set. Milliseconds(msec) – sets the year, month, hour, minute, second, and millisecond according to local time get. Time(), set. Time(time) – returns resp. sets this date to the time since 1/1/1970, 00: 00 UTC/GMT in milliseconds get. UTCDate(), set. UTCDate(day) – returns resp. sets the day (date) of the month according to universal time get. UTCDay(), set. UTCDay(day) – returns resp. sets the day of the week according to universal time get. UTCFull. Year(), get. UTCMonth(), get. UTCHours(), get. UTCMinutes(), get. UTCSeconds(), get. UTCMilliseconds() – returns the year, month, hour, minute, second, and millisecond according to universal time set. UTCFull. Year(year), set. UTCMonth(month), set. UTCHours(hour), set. UTCMinutes(minute), set. UTCSeconds(sec), set. UTCMilliseconds(msec) – sets the year, month, hour, minute, second, and millisecond according to universal time get. Timezone. Offset() – returns the time-zone offset in minutes for the current locale
18 Date Conversion Methods • • to. Locale. Date. String() – returns the date portion as a string using the current locale's conventions to. Locale. Time. String() – returns the time portion as a string using the current locale's conventions to. Locale. String() – returns date and time as a string using the current locale's conventions to. UTCString () – returns date and time as a string using the universal time convention to. Date. String() – returns the date portion as a human-readable string to. Time. String() – returns the time portion as a human-readable string to. String() – returns a string representation
19 Date Example • Compute remaining time until a certain date: var start = new Date(); var end = new Date("May 15, 2010 13: 31: 45"); var remaining = end. get. Time() - start. get. Time(); // time in milliseconds
20 Object • Object is the root of the object hierarchy – constructor property • the function that creates an object – Methods • eval(code) – evaluates code as Java. Script code (in the context of this object) – (deprecated) • to. String() – returns a string representation of this object • to. Locale. String() – same as to. String() • All objects inherit from Object, i. e. : – all objects have constructor property – all objects have to. String() function
21 Object Function • Represents a function – every JS function is a Function object – incl. the constructor function of an object • A function can be constructed as an object – new Function([param 1, …, param. N], body) • optional list of parameters param 1, …, param. N • the last parameter is the body of the function • Properties – caller • who called it (non-standard) – length • expected number of arguments – name • (non-standard)
22 Function Methods • call([param 1, …, param. N]) – calls this function • apply([parameters]) – calls this function – parameters are passed as an Array object • to. String() – returns the source code of the function as a string
23 Function Examples var add = new Function("x", "y", "return x + y"); var result = add(415, 313); // or another way result = add. call(415, 313); // or yet another way var parameters = [415, 313]; result = add. apply(parameters); function debug (name, value) { alert (debug. caller + ": " + name + "=" + value); } //now the call var some. Value; debug ("some. Value", some. Value);
24 Other Standard Objects • Array – mentioned already • Reg. Exp – see later • variety of error types – Error, Eval. Error, Range. Error, Reference. Error, Syntax. Error, Type. Error, URIError
25 OOP in JS • JS doesn't have the concept of a class • But, there is the similar concept of a prototype – prototype contains the properties of a class of objects • as a method is also a property of the object, the prototype contains all the methods, too! • Unlike in Java a prototype is very dynamic – you can add a property to a prototype • this will add the property to each object • e. g. , adding a function to a prototype will add a method to all objects of the class
26 Simple Objects • Objects can be constructed on the fly – syntax • {name 1: value 1[, …, name. N: value. N]} • e. g. : var c 1 = {real: 1. 0, imag: 0. 0} var c 2 = {real: 2. 0, imag: -2. 0} var sum = { real: c 1. real + c 1. real , imag: c 1. imag + c 1. imag} • Properties can be added to objects – syntax • object-name. property-name • e. g. : c 1. abs = Math. sqrt(c 1. real*c 1. real+c 1. imag*c 1. imag); – such properties are object-specific
27 Constructing a Prototype • A prototype is just a (constructor) function – conventions • Name of the constructor function should start with capital letter • constructor and methods are typically in a separate file called Name. js • Calling new with a function name – creates a prototype where the function is a constructor – creates an object of this prototype • Object's properties are prefixed by this. – such properties are public, i. e. visible everywhere - OOP alert!!
28 Encapsulation Via Closures • Local variables declared in constructor using var – retain their scope and lifetime – their value can be accessed and changed by functions declared within the constructor • This is the closure concept • Advantage – methods can be defined as anonymous functions – such local variables are private, i. e. inaccessible from outside – OOP: encapsulation is possible, albeit weird • Problems – each object has its own copy of the anonymous functions – garbage collection / memory leaks
29 Closure Example function Counting(init. Value) { var count = init. Value; this. inc = function () { count++; return count; } } var counting = new Counting(0); alert(counting. inc()); // outputs 1 alert(counting. inc()); // outputs 2
30 Constructor Function Example function Student(name, age, major) { this. name = name; this. age = age; this. major = major; this. to. String = function() { return this. name + " (" + this. age + "), " + this. major; } } var uh. Student = new Student("John", 24, "ICS"); alert(uh. Student); // John (24), ICS // let's add some properties to John uh. Student. uni = "UH"; uh. Student. level = "senior"; // and let's have a better output uh. Student. info = function() { return this. to. String() + " " + this. level + " at " + this. uni; }; alert(uh. Student. info()); // John (24), ICS senior at UH
31 Student Example refined var uh. Student = new Student("John", 24, "ICS"); uh. Student. uni = "UH"; uh. Student. level = "senior"; alert(uh. Student); // John (24), ICS // now let's improve to. String() itself uh. Student. info = uh. Student. to. String; uh. Student. to. String = function() { return this. info() + " " + this. level + " at " + this. uni; }; // now the output is simpler alert(uh. Student); // John (24), ICS senior at UH // improved to. String() doesn't work for another student var jack = new Student("Jack", 19, "LIS"); alert(jack); // Jack (19), LIS
32 prototype property • Is inherited by each object • Can be dynamically updated simply by assigning its new properties – e. g. • name. prototype. property = value; • New function properties can be added, too – e. g. • name. prototype. name = function (parameters) {body} • Such function can use this as reference to the object
33 prototype Examples Array. prototype. shuffle = function() { for (var i = this. length - 1; i >= 1; i--) { var j = Math. floor (Math. random () * (i + 1)); var jth. Value = this[j]; this[j] = this[i]; this[i] = jth. Value; } return this; } var shuffled = [0, 1, 2, 3, 4, 5, 6]. shuffle(); alert(shuffled); // e. g. [6, 4, 0, 3, 1, 5, 2] String. prototype. trim = function() { return = this. replace(/^s+|s+$/g, ""); } var trimmed = " alert(trimmed); nt some text fn // some text ". trim();
34 Inheritance • Main concept – the prototype chain • To append a Sub. Class to the prototype chain of Super. Class use – Sub. Class. prototype = new Super. Class(); • then Sub. Class inherits all the properties of Super. Class • including all the methods • Numerous approaches to alleviate drawbacks, e. g. : – javascript. crockford. com/inheritance. html – www. coolpage. com/developer/javascript/Correct OOP for Javascript. html – mckoss. com/jscript/object. htm • Multiple inheritance is possible
35 Polymorphism • Polymorphism – a method can have different forms – depending on the type of the object • In JS, polymorphism is automatic – simply redefine the function with the same name – Note 1: different parameter list doesn't constitute a different function • if the function name is the same, it's the same function! • unlike Java! – Note 2: two properties can't have the same name • since a function is also a property, it's name must not conflict with another property
36 Static Members • Simply add the member using the name of the constructor function – using the dot-notation • e. g. , Math. SQRT 3 = Math. sqrt(3); • e. g. , Math. sqr = function (x) {return x*x; } • Or in within a constructor function () Board. size = 8; Board. init = function () {…} }
- Slides: 36