SlideShare a Scribd company logo
1 of 31
WEB222
MORE BUILT-IN OBJECTS, CUSTOM OBJECTS &
PROTOTYPAL INHERITANCE
Announcements
• Weekly tests continue
• Assignment 2
• Due in 2 weeks (Check my.Seneca)
Agenda
• Part One
• JavaScript Objects
• Built-In Objects: Date, Math
• Part Two
• JavaScript Objects
• User-Defined Objects
• Prototypal Inheritance
Part 1
JavaScript Built-In Objects (Date & Math)
Date Object
• Enables basic storage and retrieval of dates and times.
• Creates a Date object with current date and time:
• Date string:
• Will show the date string:
• The date is Mon Mar 10 2014 09:02:37 GMT-0400 (Eastern Standard Time)
var myDate = new Date();
console.log("The date is " + myDate);
Date Object
• Creates a Date object with certain date and time:
var date1 = new Date(2001, 4, 10);
var date2 = new Date(2001, 4, 10, 11, 13, 15, 0);
var date3 = new Date("May 10, 2001 11:13:15");
console.log(date1 + "n" + date2 + "n" + date3);
// Outputs
// Thu May 10 2001 00:00:00 GMT -0400 (Eastern Daylight Time)
// Thu May 10 2001 11:13:15 GMT -0400 (Eastern Daylight Time)
// Thu May 10 2001 11:13:15 GMT -0400 (Eastern Daylight Time)
The get… Methods of Date Object
• getMonth() method
• Returns a Number - 0 to 11
• Represents the months of January through December
• e.g.
• getDate() method
• Returns a number - 1 to 31
• e.g.
var myMonth = (new Date()).getMonth();
console.log(myMonth); // The myMonth is 6 which is, July
var myDay = (new Date()).getDate();
console.log(myDay ); // outputs 3 (since this lecture is on the 3rd of June)
The get… Methods of Date Object
• getDay() method
• Returns a Number: 0 for Sunday, 1 for Monday, …
• e.g.
• getFullYear() method
• Returns a 4 digit year
• e.g.
var myDayOfWeek = (new Date()).getDay();
console.log(myDayOfWeek); // outputs 5 (since this lecture is on a Friday)
var myYear = (new Date()). getFullYear();
console.log(myYear); // 2016
The get… Methods of Date Object
• getHours() method
• Returns a number of 0 to 23
• getMinutes() method
• Returns a number of 0 to 59
• getSeconds() method
• Returns a number of 0 to 59
• getMilliseconds() method
• returns a number of 0 to 999
var myDate = new Date();
var myHour = myDate.getHours();
var myMinutes = myDate.getMinutes();
var mySeconds = myDate.getSeconds();
console.log(myHour + ":" + myMinutes + ":" + mySeconds);
// outputs 10:30:35 (If this statement was
// executed at 10:30 and 35 seconds in the morning)
Date Object – Displaying Dates as Strings
• Methods
• toString()
• toLocaleString()
• toUTCString() // UTC: Universal Time Coordinated – (ie: Standardized Time)
• toDateString()
• For Example:
var dt = new Date();
console.log(dt); // Thu Jun 02 2016 11:11:50 GMT-0400 (Eastern Daylight Time)
console.log(dt.toString()); // Thu Jun 02 2016 11:11:50 GMT-0400 (Eastern Daylight Time)
console.log(dt.toLocaleString()); // 6/2/2016, 11:11:50 AM
console.log(dt.toUTCString()); // Thu, 02 Jun 2016 15:11:50 GMT
console.log(dt.toDateString()); // Thu Jun 02 2016
Math Object - Math functions
• Math.max(ident_1, ident_2)
• the maximum of n numbers
• e.g.
• Math.min(ident_1,ident_2)
• the minimum of n numbers
• e.g.
• Math.pow(ident_1, ident2)
• ident_1 to the power ident_2
• e.g.
• Math.sqrt(ident_1)
• square root of
• e.g.
console.log( Math.max(0.52, 1) ); // 1
console.log( Math.min(0.52, 1) ); // 0.52
console.log( Math.pow(2, 8) ); // 256
console.log( Math.sqrt(9) ); // 3
Math Object – Math functions (rounding)
• Math.ceil(ident_1)
• integer closest to but not less than
• e.g.
• Math.floor(ident_1)
• integer closest to but not greater than
• e.g.
• Math.round(ident_1)
• integer closest to
• e.g.
console.log( Math.ceil(0.52) ); // 1
console.log( Math.ceil(0.49) ); // 1
console.log( Math.floor(0.52) ); // 0
console.log( Math.round(0.52) ); // 1
console.log( Math.round(0.49) ); // 0
console.log( Math.round(0.5) ); // 1
Generating Random Numbers
• Math.random()
• Generates a pseudorandom number between 0 (inclusive) and 1 (exclusive)
• e.g:
• Examples from MDN page on Math.random()
// Returns a random number between 0 (inclusive) and 1 (exclusive)
return Math.random();
// Returns a random number between min (inclusive) and max (exclusive)
return Math.random() * (max - min) + min;
// Returns a random integer between min (included) and max (excluded)
return Math.floor(Math.random() * (max - min)) + min;
// Returns a random integer between min (included) and max (included)
return Math.floor(Math.random() * (max - min + 1)) + min;
Part 2
JavaScript Objects (User-Defined Objects, Prototypal Inheritance)
Creating User-defined Objects
• As we have seen, JavaScript objects are associative arrays (or map, or dictionary - a data
structure composed of a collection of key/value pairs), augmented with prototypes.
• Object property names are string keys. They support two equivalent syntaxes:
• dot notation (obj.x = 10)
• bracket notation (obj['x'] = 10)
• Object properties and functions/methods can be added, changed, or deleted at run-time.
Creating Objects (Literal Notation)
• Using Literal Notation
var person1 = { "name": "John", "age": 30 };
// can be simplified as:
// var person1 = { name: "John", age: 30 };
var person2 = {
name: "Steven",
age: 25,
talk: function () {
console.log('I am ' + this.name + ", and I'm " + this.age + " years old.");
}
};
console.log( person1.name );
person2.talk(); // My name is Steven, and I'm 25 years old.
"this" when using Literal Notation
• The this keyword always refers to the
"execution context"
• In the previous example, the "talk" function
is always executed as a method of a "person2"
object
• Therefore, "this" refers to the "person2"
object and we can access the value of it's
properties, name & age using this.name and
this.age
var person2 = {
name: "Steven",
age: 25,
talk: function () {
console.log(this);
}
};
person2.talk();
// outputs: Object { name: "Steven", age: 25, talk: person2.talk() }
Crating Objects (Function Constructor)
• Using a Function Constructor with this and new
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.show = function () {
console.log('My name is ' + this.name + ", and I'm " + this.age + " years old.");
};
var person3 = new Person("Steven", 30);
person3.show(); // My name is Steven, and I'm 30 years old.
"this" when using Function Constructors
• Recall: The this keyword always refers to the
"execution context"
• In the previous example, the name, age &
show properties/method are declared on the
object that will eventually be created once the
"Person" function is invoked using "new".
• So, unless we specify a "new" object, "this"
refers to the global execution context, ie
"Window" when executing "Person" in a
browser
function Person(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
Person.prototype.show = function () {
console.log('My name is ' + this.name +
", and I'm " + this.age + " years old.");
};
Person("Steven", 30);
// outputs: Window
console.log(Person.age); // outputs: undefined
"new" when using Function Constructors
• The new operator creates an instance of an
object type specified by a function.
• This sets up the "this" keyword to point to the
new object (ie, "person3")
• We can inject values into the new object
instance ("person3") by passing values to the
function and assigning them by using the
"this.propertyName" syntax
function Person(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
Person.prototype.show = function () {
console.log('My name is ' + this.name +
", and I'm " + this.age + " years old.");
};
var person3 = new Person("Steven", 30);
// outputs: Object { name: "Steven", age: 30 }
console.log(person3.age); // outputs: 30
Dynamically adding properties
• Create an empty object; then dynamically add properties and methods.
var person4 = {};
// equivalent to: var person4 = new Object();
person4.name = "James";
person4.age = 30;
person4.show = function () {
console.log('My name is ' + this.name + ", and I'm " + this.age + " years old.");
};
person4.show();
Creating User-Defined Objects (Advanced)
• Usually, JavaScript object properties are
"public". This does not conform the basic
principle of OOP – Encapsulation.
• However, we can achieve encapsulation
with Closures
function Person(name, age) {
var name = name;
var age = age;
return { setName: function(newName) {name = newName;},
getName: function() { return name; },
setAge: function(newAge) { age = newAge;},
getAge: function() { return age; } };
}
var person1 = Person("John", 25); //instantiate the Person "class"
var myName = person1.getName();
console.log(myName); // John
person1.setAge(20);
console.log(person1.getAge()); //20
Prototypal Inheritance
• In JavaScript, if we wish to create a new object based on another object (ie inherit properties
and methods from another object and extend the functionality, we need to work with object
prototypes
• Note: this is unlike classical inheritance model in C++, Java, C#, etc where Classes inherit from other
Classes
• In JavaScript, objects are not based on classes.
• Prototypal Inheritance: Objects inherit from objects.
• A new object can inherit the properties and methods of an existing object.
• Existing object is used as a prototype for creating the new object.
• In effect, the new object "is a clone of the existing object."
• Note: not to be confused with the"Prototype framework" - a JS library called prototype.js.
Prototypal Chain (simplified)
• In JavaScript, all objects have an internal "__proto__" (sometimes "[[prototype]]") property
• This property refers to an object, from which the current object "inherits" properties.
• If a new object was created using Literal Notation, we have access to a global function:
Object.create(); which will allow us to create a second new object that uses the first as a
prototype (Example 1)
• If a new object was created using a Function Constructor, we have access to a public
"prototype" property which we can use to explicitly set a prototype (Example 2)
• For a more detailed explanation, see:
https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
Example 1 - Object.create()
var rectangle1 = {
width: 10,
height: 15,
show: function () {
console.log('dimensions: ' + this.width + " x " + this.height);
}
};
// creates a new rectangle using rectangle1 as prototype
var rectangle2instance = Object.create(rectangle1); // Make rectangle2 inherit from rectangle1
rectangle2instance.width = 20;
rectangle2instance.height = 25;
rectangle2instance.show(); // dimensions: 20 x 25
Example 2 - prototype property
var rectangle1 = {
width: 10,
height: 15,
show: function () {
console.log('dimensions: ' + this.width + " x " + this.height);
}
};
function rectangle2() {
this.width = 20;
this.height = 25;
}
rectangle2.prototype = rectangle1; // make rectangle2 inherit from rectangle1
var rectangle2instance = new rectangle2(); // create a new instance of rectangle2
rectangle2instance.show(); // dimensions: 20 x 25
JS OOP Example
• Model of subjects for School of ICT
• Create subject instances using the Object.create method.
var subject = {
code: "",
desc: "",
prog: [], // the prog property is an array
info: {} // the info property is an object
};
var web222 = Object.create(subject);
web222.code = 'WEB222';
web222.desc = 'Web Programming Principles';
web222.prog = ['CPD', 'CPA'];
web222.info = { hours: 4, url:' https://ict.senecacollege.ca/course/web222 ' };
JS OOP Example
var btc140 = Object.create(subject);
btc140.code = 'BTC140';
btc140.desc = 'Critical Thinking and Writing';
btc140.prog = ['BSD', 'IFS'];
btc140.info = { hours: 3, url:'https://ict.senecacollege.ca/course/ btc140' }
var ipc144 = Object.create(subject);
ipc144.code = 'IPC144';
ipc144.desc = 'Introduction to Programming Using C';
ipc144.prog = ['CPD', 'CPA', 'CTY'];
ipc144.info = { hours: 5, url: https://ict.senecacollege.ca/course/ipc144' }
var bti220 = Object.create(subject);
bti220.code = 'BTI220';
bti220.desc = 'Internet Architecture and Development';
bti220.prog = ['BSD'];
bti220.info = { hours: 4, url:' https://ict.senecacollege.ca/course/bti220' }
JS OOP Example
• All subjects
// Create a collection of all subject objects
var all = [web222, bti220, ipc144, btc140];
// Declare and initialize an accumulator
var totalHours = 0;
// Go through the collection, accumulate hours, dump to the Web Console
for (var i = 0; i < all.length; i++) {
totalHours += all[i].info.hours;
console.log(all[i]);
};
// Report the total hours
console.log('Total hours is ' + totalHours);
Useful Resource Links (from MDN)
• Introduction to Object-Oriented JavaScript | MDN
• Inheritance and the prototype chain - JavaScript | MDN
• Details of the object model - JavaScript | MDN
• Closures - JavaScript | MDN
• Standard built-in objects - JavaScript | MDN
Questions?
• Any questions?
• Would you like to see any more examples?

More Related Content

Similar to WEB222-lecture-4.pptx

みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」techtalkdwango
 
第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScriptTakuya Fujimura
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Java & OOP Core Concept
Java & OOP Core ConceptJava & OOP Core Concept
Java & OOP Core ConceptPin-Lun Huang
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180Mahmoud Samir Fayed
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
Chapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingChapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingDr. Ahmed Al Zaidy
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayJeongbae Oh
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
ActionScript
ActionScript ActionScript
ActionScript Edison
 

Similar to WEB222-lecture-4.pptx (20)

みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 
第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
Java & OOP Core Concept
Java & OOP Core ConceptJava & OOP Core Concept
Java & OOP Core Concept
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Chapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingChapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based Programming
 
Ios development
Ios developmentIos development
Ios development
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
ActionScript
ActionScript ActionScript
ActionScript
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 

WEB222-lecture-4.pptx

  • 1. WEB222 MORE BUILT-IN OBJECTS, CUSTOM OBJECTS & PROTOTYPAL INHERITANCE
  • 2. Announcements • Weekly tests continue • Assignment 2 • Due in 2 weeks (Check my.Seneca)
  • 3. Agenda • Part One • JavaScript Objects • Built-In Objects: Date, Math • Part Two • JavaScript Objects • User-Defined Objects • Prototypal Inheritance
  • 4. Part 1 JavaScript Built-In Objects (Date & Math)
  • 5. Date Object • Enables basic storage and retrieval of dates and times. • Creates a Date object with current date and time: • Date string: • Will show the date string: • The date is Mon Mar 10 2014 09:02:37 GMT-0400 (Eastern Standard Time) var myDate = new Date(); console.log("The date is " + myDate);
  • 6. Date Object • Creates a Date object with certain date and time: var date1 = new Date(2001, 4, 10); var date2 = new Date(2001, 4, 10, 11, 13, 15, 0); var date3 = new Date("May 10, 2001 11:13:15"); console.log(date1 + "n" + date2 + "n" + date3); // Outputs // Thu May 10 2001 00:00:00 GMT -0400 (Eastern Daylight Time) // Thu May 10 2001 11:13:15 GMT -0400 (Eastern Daylight Time) // Thu May 10 2001 11:13:15 GMT -0400 (Eastern Daylight Time)
  • 7. The get… Methods of Date Object • getMonth() method • Returns a Number - 0 to 11 • Represents the months of January through December • e.g. • getDate() method • Returns a number - 1 to 31 • e.g. var myMonth = (new Date()).getMonth(); console.log(myMonth); // The myMonth is 6 which is, July var myDay = (new Date()).getDate(); console.log(myDay ); // outputs 3 (since this lecture is on the 3rd of June)
  • 8. The get… Methods of Date Object • getDay() method • Returns a Number: 0 for Sunday, 1 for Monday, … • e.g. • getFullYear() method • Returns a 4 digit year • e.g. var myDayOfWeek = (new Date()).getDay(); console.log(myDayOfWeek); // outputs 5 (since this lecture is on a Friday) var myYear = (new Date()). getFullYear(); console.log(myYear); // 2016
  • 9. The get… Methods of Date Object • getHours() method • Returns a number of 0 to 23 • getMinutes() method • Returns a number of 0 to 59 • getSeconds() method • Returns a number of 0 to 59 • getMilliseconds() method • returns a number of 0 to 999 var myDate = new Date(); var myHour = myDate.getHours(); var myMinutes = myDate.getMinutes(); var mySeconds = myDate.getSeconds(); console.log(myHour + ":" + myMinutes + ":" + mySeconds); // outputs 10:30:35 (If this statement was // executed at 10:30 and 35 seconds in the morning)
  • 10. Date Object – Displaying Dates as Strings • Methods • toString() • toLocaleString() • toUTCString() // UTC: Universal Time Coordinated – (ie: Standardized Time) • toDateString() • For Example: var dt = new Date(); console.log(dt); // Thu Jun 02 2016 11:11:50 GMT-0400 (Eastern Daylight Time) console.log(dt.toString()); // Thu Jun 02 2016 11:11:50 GMT-0400 (Eastern Daylight Time) console.log(dt.toLocaleString()); // 6/2/2016, 11:11:50 AM console.log(dt.toUTCString()); // Thu, 02 Jun 2016 15:11:50 GMT console.log(dt.toDateString()); // Thu Jun 02 2016
  • 11. Math Object - Math functions • Math.max(ident_1, ident_2) • the maximum of n numbers • e.g. • Math.min(ident_1,ident_2) • the minimum of n numbers • e.g. • Math.pow(ident_1, ident2) • ident_1 to the power ident_2 • e.g. • Math.sqrt(ident_1) • square root of • e.g. console.log( Math.max(0.52, 1) ); // 1 console.log( Math.min(0.52, 1) ); // 0.52 console.log( Math.pow(2, 8) ); // 256 console.log( Math.sqrt(9) ); // 3
  • 12. Math Object – Math functions (rounding) • Math.ceil(ident_1) • integer closest to but not less than • e.g. • Math.floor(ident_1) • integer closest to but not greater than • e.g. • Math.round(ident_1) • integer closest to • e.g. console.log( Math.ceil(0.52) ); // 1 console.log( Math.ceil(0.49) ); // 1 console.log( Math.floor(0.52) ); // 0 console.log( Math.round(0.52) ); // 1 console.log( Math.round(0.49) ); // 0 console.log( Math.round(0.5) ); // 1
  • 13. Generating Random Numbers • Math.random() • Generates a pseudorandom number between 0 (inclusive) and 1 (exclusive) • e.g: • Examples from MDN page on Math.random() // Returns a random number between 0 (inclusive) and 1 (exclusive) return Math.random(); // Returns a random number between min (inclusive) and max (exclusive) return Math.random() * (max - min) + min; // Returns a random integer between min (included) and max (excluded) return Math.floor(Math.random() * (max - min)) + min; // Returns a random integer between min (included) and max (included) return Math.floor(Math.random() * (max - min + 1)) + min;
  • 14. Part 2 JavaScript Objects (User-Defined Objects, Prototypal Inheritance)
  • 15. Creating User-defined Objects • As we have seen, JavaScript objects are associative arrays (or map, or dictionary - a data structure composed of a collection of key/value pairs), augmented with prototypes. • Object property names are string keys. They support two equivalent syntaxes: • dot notation (obj.x = 10) • bracket notation (obj['x'] = 10) • Object properties and functions/methods can be added, changed, or deleted at run-time.
  • 16. Creating Objects (Literal Notation) • Using Literal Notation var person1 = { "name": "John", "age": 30 }; // can be simplified as: // var person1 = { name: "John", age: 30 }; var person2 = { name: "Steven", age: 25, talk: function () { console.log('I am ' + this.name + ", and I'm " + this.age + " years old."); } }; console.log( person1.name ); person2.talk(); // My name is Steven, and I'm 25 years old.
  • 17. "this" when using Literal Notation • The this keyword always refers to the "execution context" • In the previous example, the "talk" function is always executed as a method of a "person2" object • Therefore, "this" refers to the "person2" object and we can access the value of it's properties, name & age using this.name and this.age var person2 = { name: "Steven", age: 25, talk: function () { console.log(this); } }; person2.talk(); // outputs: Object { name: "Steven", age: 25, talk: person2.talk() }
  • 18. Crating Objects (Function Constructor) • Using a Function Constructor with this and new function Person(name, age) { this.name = name; this.age = age; } Person.prototype.show = function () { console.log('My name is ' + this.name + ", and I'm " + this.age + " years old."); }; var person3 = new Person("Steven", 30); person3.show(); // My name is Steven, and I'm 30 years old.
  • 19. "this" when using Function Constructors • Recall: The this keyword always refers to the "execution context" • In the previous example, the name, age & show properties/method are declared on the object that will eventually be created once the "Person" function is invoked using "new". • So, unless we specify a "new" object, "this" refers to the global execution context, ie "Window" when executing "Person" in a browser function Person(name, age) { this.name = name; this.age = age; console.log(this); } Person.prototype.show = function () { console.log('My name is ' + this.name + ", and I'm " + this.age + " years old."); }; Person("Steven", 30); // outputs: Window console.log(Person.age); // outputs: undefined
  • 20. "new" when using Function Constructors • The new operator creates an instance of an object type specified by a function. • This sets up the "this" keyword to point to the new object (ie, "person3") • We can inject values into the new object instance ("person3") by passing values to the function and assigning them by using the "this.propertyName" syntax function Person(name, age) { this.name = name; this.age = age; console.log(this); } Person.prototype.show = function () { console.log('My name is ' + this.name + ", and I'm " + this.age + " years old."); }; var person3 = new Person("Steven", 30); // outputs: Object { name: "Steven", age: 30 } console.log(person3.age); // outputs: 30
  • 21. Dynamically adding properties • Create an empty object; then dynamically add properties and methods. var person4 = {}; // equivalent to: var person4 = new Object(); person4.name = "James"; person4.age = 30; person4.show = function () { console.log('My name is ' + this.name + ", and I'm " + this.age + " years old."); }; person4.show();
  • 22. Creating User-Defined Objects (Advanced) • Usually, JavaScript object properties are "public". This does not conform the basic principle of OOP – Encapsulation. • However, we can achieve encapsulation with Closures function Person(name, age) { var name = name; var age = age; return { setName: function(newName) {name = newName;}, getName: function() { return name; }, setAge: function(newAge) { age = newAge;}, getAge: function() { return age; } }; } var person1 = Person("John", 25); //instantiate the Person "class" var myName = person1.getName(); console.log(myName); // John person1.setAge(20); console.log(person1.getAge()); //20
  • 23. Prototypal Inheritance • In JavaScript, if we wish to create a new object based on another object (ie inherit properties and methods from another object and extend the functionality, we need to work with object prototypes • Note: this is unlike classical inheritance model in C++, Java, C#, etc where Classes inherit from other Classes • In JavaScript, objects are not based on classes. • Prototypal Inheritance: Objects inherit from objects. • A new object can inherit the properties and methods of an existing object. • Existing object is used as a prototype for creating the new object. • In effect, the new object "is a clone of the existing object." • Note: not to be confused with the"Prototype framework" - a JS library called prototype.js.
  • 24. Prototypal Chain (simplified) • In JavaScript, all objects have an internal "__proto__" (sometimes "[[prototype]]") property • This property refers to an object, from which the current object "inherits" properties. • If a new object was created using Literal Notation, we have access to a global function: Object.create(); which will allow us to create a second new object that uses the first as a prototype (Example 1) • If a new object was created using a Function Constructor, we have access to a public "prototype" property which we can use to explicitly set a prototype (Example 2) • For a more detailed explanation, see: https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
  • 25. Example 1 - Object.create() var rectangle1 = { width: 10, height: 15, show: function () { console.log('dimensions: ' + this.width + " x " + this.height); } }; // creates a new rectangle using rectangle1 as prototype var rectangle2instance = Object.create(rectangle1); // Make rectangle2 inherit from rectangle1 rectangle2instance.width = 20; rectangle2instance.height = 25; rectangle2instance.show(); // dimensions: 20 x 25
  • 26. Example 2 - prototype property var rectangle1 = { width: 10, height: 15, show: function () { console.log('dimensions: ' + this.width + " x " + this.height); } }; function rectangle2() { this.width = 20; this.height = 25; } rectangle2.prototype = rectangle1; // make rectangle2 inherit from rectangle1 var rectangle2instance = new rectangle2(); // create a new instance of rectangle2 rectangle2instance.show(); // dimensions: 20 x 25
  • 27. JS OOP Example • Model of subjects for School of ICT • Create subject instances using the Object.create method. var subject = { code: "", desc: "", prog: [], // the prog property is an array info: {} // the info property is an object }; var web222 = Object.create(subject); web222.code = 'WEB222'; web222.desc = 'Web Programming Principles'; web222.prog = ['CPD', 'CPA']; web222.info = { hours: 4, url:' https://ict.senecacollege.ca/course/web222 ' };
  • 28. JS OOP Example var btc140 = Object.create(subject); btc140.code = 'BTC140'; btc140.desc = 'Critical Thinking and Writing'; btc140.prog = ['BSD', 'IFS']; btc140.info = { hours: 3, url:'https://ict.senecacollege.ca/course/ btc140' } var ipc144 = Object.create(subject); ipc144.code = 'IPC144'; ipc144.desc = 'Introduction to Programming Using C'; ipc144.prog = ['CPD', 'CPA', 'CTY']; ipc144.info = { hours: 5, url: https://ict.senecacollege.ca/course/ipc144' } var bti220 = Object.create(subject); bti220.code = 'BTI220'; bti220.desc = 'Internet Architecture and Development'; bti220.prog = ['BSD']; bti220.info = { hours: 4, url:' https://ict.senecacollege.ca/course/bti220' }
  • 29. JS OOP Example • All subjects // Create a collection of all subject objects var all = [web222, bti220, ipc144, btc140]; // Declare and initialize an accumulator var totalHours = 0; // Go through the collection, accumulate hours, dump to the Web Console for (var i = 0; i < all.length; i++) { totalHours += all[i].info.hours; console.log(all[i]); }; // Report the total hours console.log('Total hours is ' + totalHours);
  • 30. Useful Resource Links (from MDN) • Introduction to Object-Oriented JavaScript | MDN • Inheritance and the prototype chain - JavaScript | MDN • Details of the object model - JavaScript | MDN • Closures - JavaScript | MDN • Standard built-in objects - JavaScript | MDN
  • 31. Questions? • Any questions? • Would you like to see any more examples?