SlideShare a Scribd company logo
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

KEY
Javascript tid-bits
David Atchley
 
PDF
3.1 javascript objects_DOM
Jalpesh Vasa
 
PDF
JavaScript Essentials
Triphon Statkov
 
PDF
javascript objects
Vijay Kalyan
 
PDF
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
PPT
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
PDF
JS Level Up: Prototypes
Vernon Kesner
 
PPTX
Object oriented javascript
Usman Mehmood
 
Javascript tid-bits
David Atchley
 
3.1 javascript objects_DOM
Jalpesh Vasa
 
JavaScript Essentials
Triphon Statkov
 
javascript objects
Vijay Kalyan
 
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
JS Level Up: Prototypes
Vernon Kesner
 
Object oriented javascript
Usman Mehmood
 

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

PPTX
Object Oriented JavaScript
Julie Iskander
 
PPTX
Javascript Objects Deep Dive
Manish Jangir
 
PPT
Advanced Javascript
Manikanda kumar
 
PPT
Advanced Javascript
Adieu
 
PPT
Advanced Javascript
relay12
 
PPT
Object Oriented JavaScript
Donald Sipe
 
PPTX
Oojs 1.1
Rodica Dada
 
ODP
Javascript
theacadian
 
PPTX
Object Oriented Javascript part2
Usman Mehmood
 
PDF
Prototype
Aditya Gaur
 
PPTX
Javascript Objects and Functions
Gitanjali wagh
 
PPTX
Javascript Objects and Functions
Manoj \/ishwakarma
 
PPT
Advanced JavaScript
Fu Cheng
 
PPTX
JavaScript OOPS Implimentation
Usman Mehmood
 
PPTX
Ajaxworld
deannalagason
 
PPTX
Advanced JavaScript
Zsolt Mészárovics
 
PDF
java script functions, classes
Vijay Kalyan
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PDF
JavaScript Core
François Sarradin
 
Object Oriented JavaScript
Julie Iskander
 
Javascript Objects Deep Dive
Manish Jangir
 
Advanced Javascript
Manikanda kumar
 
Advanced Javascript
Adieu
 
Advanced Javascript
relay12
 
Object Oriented JavaScript
Donald Sipe
 
Oojs 1.1
Rodica Dada
 
Javascript
theacadian
 
Object Oriented Javascript part2
Usman Mehmood
 
Prototype
Aditya Gaur
 
Javascript Objects and Functions
Gitanjali wagh
 
Javascript Objects and Functions
Manoj \/ishwakarma
 
Advanced JavaScript
Fu Cheng
 
JavaScript OOPS Implimentation
Usman Mehmood
 
Ajaxworld
deannalagason
 
Advanced JavaScript
Zsolt Mészárovics
 
java script functions, classes
Vijay Kalyan
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
JavaScript Core
François Sarradin
 
Ad

Recently uploaded (20)

PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
CDH. pptx
AneetaSharma15
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
CDH. pptx
AneetaSharma15
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Ad

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?