Presentation is loading. Please wait.

Presentation is loading. Please wait.

6. JavaScript Objects and Object- Oriented Programming (OOP)

Similar presentations


Presentation on theme: "6. JavaScript Objects and Object- Oriented Programming (OOP)"— Presentation transcript:

1 6. JavaScript Objects and Object- Oriented Programming (OOP)

2 2 Motto: My object all sublime I shall achieve in time. —W. S. Gilbert

3 3 JavaScript & OOP JavaScript 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 classe) –you can – and should define your own objects

4 4 JavaScript Objects Objects have –a type the type has a name –attributes properties –behaviors functions in JavaScript, functions are properties, too!

5 5 Object-Oriented Design Uses software models that define objects similar to the real- world 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

6 6 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

7 7 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

8 8 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, LN2, LN10, SQRT2, SQRT1_2, LOG2E, LOG10E –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 xToYth = Math.pow(x,y);

9 9 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 fromCharCode() e.g., String.fromCharCode(65,66,67,68) creates "ABCD" –concatenation operator + any type concatenated with a string will be converted to a string using its toString() 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)

10 10 String Methods charAt(index) –returns the character at index –Indices start at 0 and go to length-1 –returns an empty string if index >= length charCodeAt(index) –returns the Unicode value of the character at index –returns NaN if index >= length toLowerCase(), toUpperCase() –returns the lowercase resp. uppercase version of this string toLocaleLowerCase() toLocaleUpperCase() –returns the uppercase lowercase resp. version of this string according to current locale indexOf(pattern[,startIndex]) –returns the beginning index of the first occurrence of pattern –returns -1 if pattern is not found –starts search at startIndex if it is given lastIndexOf(pattern[,startIndex]) –returns the beginning index of the last occurrence of pattern –returns -1 if pattern is not found –starts search at startIndex if it is given

11 11 String Methods (cont.) concat(string2[,...,stringN]) –appends string2 to stringN 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,string2) –returns a string where the pattern within this string has been replaced by string2 –this string remains unchanged localeCompare(string2) –returns 1 if this string > string2, -1 if this string < string2, and 0 if the strings are equal –uses locale-specific ordering (e.g., "aaa" < "ZZZ" )

12 12 String Substring Methods substring(from[,to]) –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 substr(from[,n]) –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)

13 13 String RegExp Methods search(regexp) –returns the index of the first occurrence of the pattern matching the of regular expression regexp within this string string2 –returns -1 if the pattern doesn't occur in this string –same as indexOf(pattern), except that it uses a regular expression replace(regexp,string2) –returns a string where the occurrence of the pattern matching the of regular expression regexp within this string has been replaced by string2 –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)

14 14 String Wrapper Methods Don't use these, use CSS instead – link(url) returns this string wrapped into – anchor(anchor) returns this string wrapped into – bold() returns this string wrapped into – italics() returns this string wrapped into – fixed() returns this string wrapped into – blink() returns this string wrapped into – strike() returns this string wrapped into – sub() returns this string wrapped into – sup() returns this string wrapped into – big() returns this string wrapped into – small() returns this string wrapped into – fontcolor(color) returns this string wrapped into – fontsize(size) returns this string wrapped into

15 15 Object Number Constants – MAX_VALUE, MIN_VALUE, NaN – NEGATIVE_INFINITY, POSITIVE_INFINITY special values representing returned on overflow –Used as static members, e.g., Number.MAX_VALUE Only inherited methods – toString() Used automatically in string concatenation or when conversion is needed e.g., var number = 6; alert(number);

16 16 Object Boolean Wrapper for boolean values Don't use, it only creates confusion! –e.g., var isFalse = new Boolean (false); if (isFalse) {alert("isFalse is true") } else {alert("isFalse is false")} –will output isFalse is true !! because isFalse is an object and an object within a condition corresponds to true

17 17 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(msecsSince1970) creates object with time in milliseconds after 1/1/1970 00:00:00 UTC/GMT Static method Date.now() –returns number of milliseconds since 1/1/1970 00:00:00 UTC/GMT non-standard

18 18 Date Accessor Methods getDate(), setDate(day) –returns resp. sets the day of the month according to local time getDay(), setDay(day), –returns resp. sets the day of the week according to local time getFullYear(), getMonth(), getHours(), getMinutes(), getSeconds(), getMilliseconds() –returns the year, month, hour, minute, second, and millisecond according to local time setFullYear(year), setMonth(month), setHours(hour), setMinutes(minute), setSeconds(sec), setMilliseconds(msec) –sets the year, month, hour, minute, second, and millisecond according to local time getTime(), setTime(time) –returns resp. sets this date to the time since 1/1/1970, 00:00:00 UTC/GMT in milliseconds getUTCDate(), setUTCDate(day) –returns resp. sets the day (date) of the month according to universal time getUTCDay(), setUTCDay(day) –returns resp. sets the day of the week according to universal time getUTCFullYear(), getUTCMonth(), getUTCHours(), getUTCMinutes(), getUTCSeconds(), getUTCMilliseconds() –returns the year, month, hour, minute, second, and millisecond according to universal time setUTCFullYear(year), setUTCMonth(month), setUTCHours(hour), setUTCMinutes(minute), setUTCSeconds(sec), setUTCMilliseconds(msec) –sets the year, month, hour, minute, second, and millisecond according to universal time getTimezoneOffset() –returns the time-zone offset in minutes for the current locale

19 19 Date Conversion Methods toLocaleDateString() –returns the date portion as a string using the current locale's conventions toLocaleTimeString() –returns the time portion as a string using the current locale's conventions toLocaleString() –returns date and time as a string using the current locale's conventions toUTCString () –returns date and time as a string using the universal time convention toDateString() –returns the date portion as a human-readable string toTimeString() –returns the time portion as a human-readable string toString() –returns a string representation

20 20 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.getTime() - start.getTime(); // time in milliseconds

21 21 Object Object is the root of the object hierarchy – constructor property the function that creates an object –Methods eval(code) –evaluates code as JavaScript code (in the context of this object) –(deprecated) toString() –returns a string representation of this object toLocaleString() –same as toString() All objects inherit from Object, i.e.: –all objects have constructor property –all objects have toString() function

22 22 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([param1,…,paramN],body) optional list of parameters param1,…,paramN the last parameter is the body of the function Properties – caller who called it (non-standard) – length expected number of arguments – name (non-standard)

23 23 Function Methods call([param1,…,paramN]) –calls this function apply([parameters]) –calls this function – parameters are passed as an Array object toString() –returns the source code of the function as a string

24 24 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 someValue; debug ("someValue", someValue);

25 25 Other Standard Objects Array –mentioned already RegExp –see later variety of error types – Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError

26 26 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

27 27 Simple Objects Objects can be constructed on the fly –syntax {name1:value1[,…,nameN:valueN]} e.g.: var c1 = {real: 1.0, imag: 0.0} var c2 = {real: 2.0, imag: -2.0} var sum = { real: c1.real + c1.real, imag: c1.imag + c1.imag} Properties can be added to objects –syntax object-name.property-name e.g.: c1.abs = Math.sqrt(c1.real*c1.real+c1.imag*c1.imag); –such properties are object-specific

28 28 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!!

29 29 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 Problems –each object has its own copy of the anonymous functions –garbage collection / memory leaks

30 30 Closure Example function Counting(initValue) { var count = initValue; this.inc = function () { count++; return count; } var counting = new Counting(0); alert(counting.inc()); // outputs 1 alert(counting.inc()); // outputs 2

31 31 Constructor Function Example function Student(name, age, major) { this.name = name; this.age = age; this.major = major; this.toString = function() { return this.name + " (" + this.age + "), " + this.major; } var uhStudent = new Student("John", 24, "ICS"); alert(uhStudent); // John (24), ICS // let's add some properties to John uhStudent.uni = "UH"; uhStudent.level = "senior"; // and let's have a better output uhStudent.info = function() { return this.toString() + " " + this.level + " at " + this.uni; }; alert(uhStudent.info()); // John (24), ICS senior at UH

32 32 Student Example refined var uhStudent = new Student("John", 24, "ICS"); uhStudent.uni = "UH"; uhStudent.level = "senior"; alert(uhStudent); // John (24), ICS // now let's improve toString() itself uhStudent.info = uhStudent.toString; uhStudent.toString = function() { return this.info() + " " + this.level + " at " + this.uni; }; // now the output is simpler alert(uhStudent); // John (24), ICS senior at UH // improved toString() doesn't work for another student var jack = new Student("Jack", 19, "LIS"); alert(jack); // Jack (19), LIS

33 33 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

34 34 prototype Examples Array.prototype.shuffle = function() { for (var i = this.length - 1; i >= 1; i--) { var j = Math.floor (Math.random () * (i + 1)); var jthValue = this[j]; this[j] = this[i]; this[i] = jthValue; } 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 = " \n\t some text \f\n ".trim(); alert(trimmed); // some text

35 35 Inheritance Main concept –the prototype chain To append a SubClass to the prototype chain of SuperClass use – SubClass.prototype = new SuperClass(); then SubClass inherits all the properties of SuperClass 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 See examples later

36 36 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

37 37 Static Members Simply add the member using the name of the constructor function –using the dot-notation e.g., Math.SQRT3 = Math.sqrt(3); e.g., Math.sqr = function (x) {return x*x;} Or in within a constructor function () Board.size = 8; Board.init = function () {…} }


Download ppt "6. JavaScript Objects and Object- Oriented Programming (OOP)"

Similar presentations


Ads by Google