0% found this document useful (0 votes)
93 views58 pages

Js 2

The document discusses object oriented programming concepts in JavaScript like objects, classes, encapsulation and inheritance. It provides examples of creating objects and classes in JavaScript. Objects can store key-value pairs and classes act as blueprints for objects. Encapsulation wraps properties and methods within a class while inheritance allows one class to inherit features of another.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views58 pages

Js 2

The document discusses object oriented programming concepts in JavaScript like objects, classes, encapsulation and inheritance. It provides examples of creating objects and classes in JavaScript. Objects can store key-value pairs and classes act as blueprints for objects. Encapsulation wraps properties and methods within a class while inheritance allows one class to inherit features of another.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Object Oriented Programming (OOP) in JS

 As JavaScript is widely used in Web Development and some of


the Object Oriented mechanisms supported by JavaScript.

 There are certain features or mechanisms which makes a Language


Object-Oriented like: 
1. Object
2. Classes
3. Encapsulation
4. Inheritance
Object Oriented Programming (OOP) in JS

 Object
By using arrays we can store a group of individual objects and it is not
possible to store key-value pairs.
If we want to represent a group of key-value pairs then we should go for
Objects.
Array: A group of individual objects []
Object: A group of key-value pairs {}
JavaScript objects store information in the form of key-value pairs.

An Object is an instance of a class.


Object Oriented Programming (OOP) in JS
To create empty object:
var nums={}
OR
var nums=new Object()
1st Way: 2nd Way:

nums["fno"]=100 nums.fno=100

nums["sno"]=200 nums.sno=200

var variableName={ key1:value1,key2:value2,...};

var college={ name:‘CBIT', year: 1979, Dept:‘IT' };


Object Oriented Programming (OOP) in JS

var College=[“CBIT",“MGIT",“VCE",“VNRVJIET"]; var college={ name:‘CBIT', year: 1979, Dept:‘IT' };


Object Oriented Programming (OOP) in JS
//Defining object
let person =
{
    first_name:'CBIT',
    last_name: 'MGIT',
    //function
    getFunction ()
{
        return (`The name of the person is${person.first_name} ${person.last_name}`)
    },
    //object within object
    phone_number :
{
     mobile:'12345',
        landline:'6789'
   }
}
console.log(person.getFunction());
console.log(person.phone_number.landline);
Object Oriented Programming (OOP) in JS
Classes–:

Classes are blueprint of an Object. 

JavaScript classes, introduced in ECMAScript 2015

JavaScript Class Syntax

1. Use the keyword class to create a class.

2. Always add a method named constructor():

class ClassName

constructor() { ... }

}
Object Oriented Programming (OOP) in JS
// Defining class using es6
class Vehicle
{
    constructor(name, maker, engine)
  {
        this.name = name;
        this.maker = maker;
        this.engine = engine;
  }
    getDetails()
  {
        return (`The name of the bike is ${this.name}.`)
  }
}
    // Making object with the help of the constructor
    let bike1 = new Vehicle(A', 'Suzuki', '1340cc');
    let bike2 = new Vehicle(B', 'Kawasaki', '998cc');
  
    console.log(bike1.name);
    console.log(bike2.maker);
    console.log(bike1.getDetails());
  
Object Oriented Programming (OOP) in JS
 Encapsulation:The process of wrapping properties and functions within a single unit is known as encapsulation. 
class person
{
    constructor(name,id)
  {
        this.name = name;
        this.id = id;
  }
    add_Address(add)
  {
        this.add = add;
  }
    getDetails()
  {
        console.log(`Name is ${this.name},Address is: ${this.add}`);
  }
}

let person1 = new person(‘abc',30);


person1.add_Address('Hyderabad');
person1.getDetails();
Object Oriented Programming (OOP) in JS

 Inheritance – It is a concept in which some properties and methods of an Object

are being used by another Object.

 Unlike most of the OOP languages where classes inherit classes, JavaScript

Objects inherit Objects i.e. certain features (property and methods) of one object

can be reused by other Objects.


Object Oriented Programming (OOP) in JS
//Inheritance example
class person
{
    constructor(name)
  {
        this.name = name;
  }
    //method to return the string
    toString(){       return (`Name of person: ${this.name}`); }
}
class student extends person
{
    constructor(name,id)
  {
        //super keyword for calling the above class constructor
        super(name);
        this.id = id;
  }
    toString()
  {
        return (`${super.toString()},Student ID: ${this.id}`);
  }
}
let student1 = new student('Abhilan',22);
console.log(student1.toString());
Document Object Model (DOM)
 DOM acts as interface between JavaScript and HTML, CSS.

 Browser will construct DOM.

 All HTML tags will be stored as JavaScript objects.

t
Document Object Model (DOM)
https://software.hixie.ch/utilities/js/live-dom-viewer/
Document Object Model (DOM)
To display Document to the console:
Just type on JavaScript console: document
Then we will get total HTML Page/Document.
To Display DOM Objects on the Console:
console.dir(document)
Observe that Root element of DOM is document.
DOM Attributes:
1) document.URL :This is original URL of the website.
2) document.body :It returns everything inside body.
3) document.head :It returns head of the page.
4) document.links :It returns list of all links of the page.
Document Object Model (DOM)

How to grab HTML Elements from the DOM?


1) document.getElementById()
Returns element with the specified id.
2) document.getElementsByClassName()
Returns list of all elements belongs to the specified class.
3) document.getElementsByTagName()
Returns list of all elements with the specified tag.
4) document.querySelector()
Returns the first object matching CSS style selector.
5) document.querySelectorAll()
Returns all objects Matches the CSS Style Selector.
JavaScript Regular Expressions
 In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence
of characters used for defining a search pattern.
/^a...s$/

 The pattern is: any five letter string starting with a and ending with s.
https://regex101.com/
Create a RegEx
 Using a regular expression literal:
const regularExp = /abc/;
 Using the RegExp() constructor function:
const reguarExp = new RegExp('abc');
JavaScript Regular Expressions

Using String Methods

 In JavaScript, regular expressions are often used with the two string methods: search() and replace().

 The search() method uses an expression to search for a match, and returns the position of the match.
1. The search method returns the position in the String object at which the pattern matched.
2. If there is no match, search returns –1.
3. The position of the first character in the string is 0.

 The replace() method returns a modified string where the pattern is replaced.
JavaScript Regular Expressions

var str = "Rabbits are furry";

var position = str.search(/bits/g);

if (position >= 0)

document.write("'bits' appears in position", position,"<br />");

else

document.write("'bits' does not appear in str <br />");

output:

'bits' appears in position 3


JavaScript Regular Expressions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with “Google" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction()
{
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.replace("Microsoft",“Google");
}
</script>
</body>
</html>
JavaScript Regular Expressions
Method Description

Executes a search for a match in a string and returns an array of information. It returns
exec()
null on a mismatch.

test() Tests for a match in a string and returns true or false.

match() Returns an array containing all the matches. It returns null on a mismatch.

matchAll() Returns an iterator containing all of the matches.

Tests for a match in a string and returns the index of the match. It returns -1 if the
search()
search fails.

Searches for a match in a string and replaces the matched substring with a replacement
replace()
substring.

split() Break a string into an array of substrings.


JavaScript Regular Expressions
const string = 'Find me';
const pattern = /me/;
// search if the pattern is in string variable
const result1 = string.search(pattern);
console.log(result1); // 5
// replace the character with another character
const string1 = 'Find me';
string1.replace(pattern, 'found you'); // Find found you
// splitting strings into array elements
const regex1 = /[\s,]+/;
const result2 = 'Hello world! '.split(regex1);
console.log(result2); // ['Hello', 'world!', '']
// searching the phone number pattern
const regex2 = /(\d{3})\D(\d{3})-(\d{4})/g;
const result3 = regex2.exec('My phone number is: 555 123-4567.');
console.log(result3); // ["555 123-4567", "555", "123", "4567"]
JavaScript Regular Expressions
MetaCharacters are characters that are interpreted in a special way by a RegEx engine.

[] - Square brackets -Square brackets specify a set of characters you wish to match.

. - Period-A period matches any single character (except newline '\n').

^ - Caret-The caret symbol ^ is used to check if a string starts with a certain character.

$ - Dollar-The dollar symbol $ is used to check if a string ends with a certain character.

* - Star-The star symbol * matches zero or more occurrences of the pattern left to it.

+ - Plus-The plus symbol + matches one or more occurrences of the pattern left to it.

? - Question Mark -The question mark symbol ? matches zero or one occurrence.

| - Alternation- Vertical bar | is used for alternation (or operator).


JavaScript Regular Expressions

/\d\.\d\d/ // Matches a digit, followed by a period, // followed by two digits.

/\D\d\D/ // Matches a single digit.

/\w\w\w/ // Matches three adjacent word characters


What is Event Handling?
• Capturing events and responding to them

• The system sends events to the program and the program


responds to them as they arrive

• Events can include things a user does - like clicking the


mouse - or things that the system itself does - like updating
the clock. Today we will exclusively focus on user-events

23
Event Driven Programs
• Programs that can capture and respond to events are called
‘event-driven programs’

• JavaScript was specifically designed for writing such


programs

• Almost all programs written in JavaScript are event-driven

24
JavaScript Handling of Events
• Events handlers are placed in the BODY part of a Web page
as attributes in HTML tags

• Events can be captured and responded to directly with


JavaScript one-liners embedded in HTML tags in the BODY
portion

• Alternatively, events can be captured in the HTML code, and


then directed to a JavaScript function for an appropriate
response

25
26
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function checkForm() {
if ( document.sendEmail.sender.value.length < 1) {
window.alert( “Empty From field! Please correct” );
}
}

JavaScript included as an attribute of the “Send eMail” button:

onMouseOver=“checkForm( )”

27
Usage Guideline
• For very short scripts, “all code in the tag” works well

• The “code in the HEAD portion” is the right choice for


developing larger JavaScript scripts
• It makes the code easier to read
• It allows the reuse of a function for multiple event handlers

28
29
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function vuWindow() {
window.open(“http://www.vu.edu.pk/”) ;
}

JavaScript included as an attribute of the “New Window” button:

onClick=“vuWindow()”

30
A Few of Favorite Event Handlers
onClick
onDblClick
onMouseOver
onMouseDown
onFocus
onBlur
onReset
onSubmit
onLoad
onUnload
31
onFocus & onBlur
• onFocus executes the specified JavaScript code when a
window receives focus or when a form element receives
input focus

• onBlur executes the specified JavaScript code when a


window loses focus or a form element loses focus

32
33
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function checkAge( ) {
if( parseInt( document.form1.age.value ) < 12 ) {
window.alert( "Stop! You are younger than 12" ) ;
}
}

JavaScript included as an attribute of the INPUT tag:

<INPUT type="text" name="age"


onBlur="checkAge( ) "
> 34
<HTML><HEAD>
<TITLE>onBlur( ) Demo</TITLE>
<SCRIPT>
function checkAge() {
if( parseInt(document.form1.age.value) < 12) {
window.alert("Stop! You are younger than 12" ) ;
}
}
</SCRIPT></HEAD>
<BODY bgcolor="#66FFCC">
<FORM name="form1" method="post" action="">
<TABLE border="1">
<TR> <TD>Age</TD>
<TD><INPUT type="text" name="age" onBlur="checkAge()">
</TD></TR><TR> <TD>Phone Number</TD>
<TD><INPUT type="text" name="phNo"></TD>
</TR><TR> <TD><INPUT type="reset" value="Reset"></TD>
<TD><INPUT type="submit" value="Submit"></TD></TR>
</TABLE></FORM></BODY></HTML>
35
onLoad & onUnload
• onLoad executes the specified JavaScript code when a new
document is loaded into a window

• onUnload executes the specified JavaScript code when a


user exits a document

36
http://www.vu.edu.pk/
onUnloadDemo.htm

37
<HTML>
<HEAD>
<TITLE>onUnload Demo</TITLE>
<SCRIPT>
function annoyUser( ) {
currentUrl = window.location ;
window.alert( "You can't leave this page" ) ;
window.location = currentUrl ;
}
</SCRIPT></HEAD>
<BODY onUnload="annoyUser( )">
This page uses the onUnload event handler …
</BODY></HTML>
38
<HTML>
<HEAD>
<TITLE>onUnload Demo</TITLE>
<SCRIPT>
function annoyUser( ) {
currentUrl = window.location ;
window.alert( "You can't leave this page" ) ;
window.location = currentUrl ;
}
</SCRIPT></HEAD>
<BODY onUnload="annoyUser( )">
This page uses the onUnload event handler …
</BODY></HTML>
39
More Uses for onLoad/onUnload?
• onLoad can be used to open multiple Windows when a
particular document is opened

• onUnload can be used to say “Thank you for the visit” when
a user is leaving a Web page

• At times, a user opens multiple inter-dependent windows of


a Web site (e.g. VULMS). onUnload can be used to warn
that all child Windows will become inoperable if the user
closes the parent Window

40
A Note on Syntax (2)
• At times, you may wish to use event handlers in JavaScript
code enclosed in <SCRIPT>, </SCRIPT> tags

• In those cases you have to strictly follow the JavaScript rule


for all event handler identifiers: they must all be typed in
small case, e.g. ‘onclick’ or ‘onmouseover’

41
A misleading statement from Lecture 18
• I stated:
JavaScript is case sensitive. Only the first of the following
will result in the desired function – the rest will generate
errors or other undesirable events:
• onMouseClick – OnMouseClick
• onmouseclick – ONMOUSECLICK

• That statement is incorrect in two ways:


1. All four will work fine as part of HTML tags
2. Only the ‘all small case’ version will be interpreted as intended in
JavaScript code

42
JavaScript Functions and Events
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript Functions and Events

The change in the state of an object is known as an Event.

Mouse events

Keyboard events

Form events

Window/Document events

 
JS Mouse events
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


JS Keyboard/Form events
Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

When the user modifies or changes the value of a form


change onchange
element
JS Window/Document Events
Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser unloads it

resize onresize When the visitor resizes the window of the browser

load onload When the browser finishes the loading of the page
JavaScript Events and Objects

Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form

onClick Button, Checkbox, Submit, Reset, Link


JavaScript Click Event
<html>  
<head> Javascript Events </head>  
<body>  
<script language="Javascript" type="text/Javascript">  
     <!--  
     function clickevent()  
     {  
         document.write(“CBIT");  
     }  
     //-->  
</script>  
<form>  
<input type="button" onclick="clickevent()" value="Who's this?"/>  
</form>  
</body>  
</html>  
JavaScript Mouse Event
<html>  
<head>   
<h1> Javascript Events </h1>  
</head>  
<body>  
<script language="Javascript" type="text/Javascript">  
     <!--  
     function mouseoverevent()  
     {  
         alert(“CBIT”);  
     }  
     //-->  
</script>  
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>  
</body>  
</html>  
JavaScript Focus Event
<html>  
<head> Javascript Events</head>  
<body>  
<h2> Enter something here</h2>  
<input type="text" id="input1" onfocus="focusevent()"/>  
<script>  
<!--  
     function focusevent()  
     {  
         document.getElementById("input1").style.background=“yellow";  
     }  
//-->  
</script>  
</body>  
</html>  
JavaScript Keydown Event
<html>  
<head> Javascript Events</head>  
<body>  
<h2> Enter something here</h2>  
<input type="text" id="input1" onkeydown="keydownevent()"/>  
<script>  

     function keydownevent()  
     {  
         document.getElementById("input1");  
         alert("Pressed a key");  
     }  

</script>  
</body>  
</html>  
JavaScript Load Event
<html>  
<head>Javascript Events</head>  
</br>  
<body onload="window.alert('Page successfully loaded');">  
<script>  
<!--  
document.write("The page is loaded successfully");  
//-->  
</script>  
</body>  
</html>  
JavaScript Strings
JavaScript strings are for storing and manipulating text.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
let text = "John Doe"; // String written inside quotes
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Strings
Method Description

charAt(index) returns the character at the specified index

concat() joins two or more strings

replace() replaces a string with another string

split() converts the string to an array of strings

substr(start, length) returns a part of a string

substring(start,end) returns a part of a string

slice(start, end) returns a part of a string

toLowerCase() returns the passed string in lower case

toUpperCase() returns the passed string in upper case

trim() removes whitespace from the strings

includes() searches for a string and returns a boolean value

search() searches for a string and returns a position of a match


JavaScript Strings
const text1 = 'hello';
const text2 = 'world';
const text3 = '     JavaScript    ';

console.log(text1.concat(' ', text2)); // "hello world"


console.log(text1.toUpperCase()); // HELLO
console.log(text3.trim()); // JavaScript
console.log(text1.split()); // ["hello"]
console.log(text1.slice(1, 3)); // "el"
console.log(text3.search("Script")); //9
console.log(text1.charAt("2"));   //l
console.log(text1.substr(0,3));     //hel
console.log(text1.substring(0,4));  //hell
JS Date and Time

In JavaScript, date and time are represented by the Date object.

The Date object provides the date and time information and also provides
various methods.
Creating Date Objects
new Date()
new Date(milliseconds)
new Date(Date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JS Date and Time
const timeNow = new Date();
console.log(timeNow); // shows current date and time

const time1 = new Date(0);


console.log(time1); // Thu Jan 01 1970 05:30:00

const time2 = new Date(100000000000)


console.log(time2); // Sat Mar 03 1973 15:16:40

const date1 = new Date("2020-07-01");


console.log(date1); // Wed Jul 01 2020 05:45:00 GMT+0545
const date2 = new Date("2020-07-01T12:00:00Z");
console.log(date2); // Wed Jul 01 2020 17:45:00 GMT+0545

const time3 = new Date(2020, 2, 20, 4, 12, 11, 0);


console.log(time3); // Thu Feb 20 2020 04:12:11

You might also like