3JS-Part3 Objects, Properties, and Methods of The DOM
3JS-Part3 Objects, Properties, and Methods of The DOM
All instances
5 Prepared by: Dr. Alimatu - Saadia Yussiff
of an object are objects themselves!
‘Property’ Values of the Instances May Differ
6
Prepared by: Dr. Alimatu - Saadia Yussiff
Working with objects
JavaScript is designed on a simple object-based paradigm.
An object is a collection of properties.
A property is an association between a name (or key) and a
value. Defines the object’s characteristics.
A property's value can be a function, in which case the
property is known as a method.
A JavaScript object has properties associated with it.
Object properties are basically the same as variables,
The properties of an object define the characteristics of the
object.
Working with objects
JavaScript Objects are Mutable.
They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:
const x = person; // Will not create a copy of person.
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
Example:
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
const x = person;
x.age = 10; // Will change both x.age and person.age
How to Create new objects
1. Create a single object, using an object literal.
2. Using an object initializer.
3. Creating a constructor function and then instantiate an object by
invoking that function with the new operator.
Create an object with these two steps:
i. Define the object type by writing a constructor function. There is a
strong convention to use a capital initial letter.
ii. Create an instance/single object with keyword new Object().
4. Using the Object.create() method
These are Explained Next
How to Create new objects – (Cont.)
1. Using an Object Literal const person = {
This is the easiest way to create a JavaScript firstName: "John",
Object. lastName: "Doe",
Using an object literal, you both define and age: 50,
create an object in one statement.
eyeColor: "blue"
An object literal is a list of name:value pairs
};
(like age:50) inside curly braces {}.
Example This example creates an empty JavaScript
object, and then adds 4 properties:
const person = {firstName:"John",
lastName:"Doe", age:50, const person = { };
eyeColor:"blue"}; person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
How to Create new objects – (Cont.)
2. Using the JavaScript Keyword, new
The following example create a new JavaScript object using new
Object(), and then adds 4 properties:
Example
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
How to Create new objects – (Cont.)
3. Using an object initializer
The syntax:
const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
"property n": value3, // or a string
};
Example: The following statement creates an object and assigns it to
the variable x if and only if the expression cond is true:
const myHonda = { let x;
color: "red", if (cond) {
x = { greeting: "hi there" };
}
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
How to Create New Objects – (Cont.)
4. Creating a constructor function and You can rewrite the definition of Car to
then instantiate an object by invoking that function include an owner property that takes a
Person object, as follows:
with the new operator.
function Car(make, model, year, owner) {
The syntax:
this.make = make;
Create an object with these two steps:
Define the object type by writing a constructor this.model = model;
function. use a capital initial letter. this.year = year;
Create an instance of the object with new.
this.owner = owner;
Example:
}
function Car(make, model, year) {
Instantiating the new objects
this.make = make;
this.model = model; const car1 = new Car("Eagle", "Talon TSi",
this.year = year; } 1993, rand);
//Now you can create an object called myCar as follows: const car2 = new Car("Nissan", "300ZX",
const myCar = new Car("Eagle", "Talon TSi", 1993); 1992, ken);
// You can create any number of Car objects by calls to new
const kenscar = new Car("Nissan", "300ZX", 1992);
const vpgscar = new Car("Mazda", "Miata", 1990);
How to Create New Objects – (Cont.)
An object can have a property that is itself another object. For example,
suppose you define an object called Person as follows:
console.log(person['last name']);
Method Shorthand Syntax
The method is created with a function keyword after a colon shorthand syntax
function sayHi() {
console.log(`Hello, my name is ${this.name}`);
}
Defining getters and setters
A getter is a function associated with a property that gets the
value of a specific property.
A setter is a function associated with a property that sets the
value of a specific property.
Together, they can indirectly represent the value of a property.
fruit.name = "grape";
console.log(fruitbear); // { name:
"grape" }; not { name: "apple" }
Activity 1
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p>Access a property with ["property"]:</p>
<p id="demo"></p>
<script>
const person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};
document.getElementById("demo").innerHTML = person["firstname"] + " is " +
person["age"] + " years old.";
</script>
</body> </html>
Understanding Objects
Objects in JavaScript are a collection of properties, each of
which can contain a value.
Each value stored in the properties can be a value, another
object, or even a function.
You can define your own objects with JavaScript, or use the
several built-in objects.
The constructor for a new String object takes as its argument the
initial string:
The property length returns the length of the string. For the
example below, mylength would equal 14.
mylength = myString.length;
String Object Methods
charAt(index) – returns the character at the position in the string referred to
by index.
charCodeAt(index) – returns the Unicode value of the character at the
position in the string referred to by index.
fromCharCode(num1,...,numN) – creates a string from the sequence of
Unicode values passed to it as arguments.
toLowerCase( ) – converts all of the characters in the string to lower case.
toUpperCase( ) – converts all of the characters in the string to upper case.
indexOf(character [, start_index]) – returns the index of the first
occurrence of the specified character. If start_index is used, search begins from
that point in the string.
lastIndexOf(character [, start_index]) – returns the index of the first
occurrence of the specified character. If start_index is used, search begins from
that point in the string.
split(delimiter) – splits a string into substrings and returns an array that
contains the resulting substrings.
Formatting Methods of String
There are some methods of the object String that when used in
conjunction with an output method will create HTML like
formatting.
For example, the method sub() will cause the text to be outputted as
a subscript:
The set of all events which may occur and the page
elements on which they can occur is part of the
Document Object Model(DOM) not JavaScript.
Browsers don’t necessarily share the same set of events
Object Models (continued)
As stated earlier, JavaScript is an object-based language.
Can you name some objects related to the client viewing
a page?
To support standard implementation across all browsers
and applications, a set of object models has been created
for use with JavaScript.
Browser Object Model (BOM)
Document Object Model (DOM)
The Document Object Model
When a document is loaded in the web browser, a number of
objects are created. Most commonly used are window and document
Window
open(), close(), alert(), confirm(), prompt()
Document
Contains arrays which store all the components of your page
You can access and call methods on the components using the arrays
An object may also be accessed by its name
document.myform.address.value = “123 Main”
document.myform.reset()
Can also search for element by name or id
document.getElementById(“myelementid”)
document.getElementByName(“myelementname”)
53
Prepared by: Dr. Alimatu - Saadia Y
Object Models
JavaScript provides access to a number of
different components on the client’s side:
HTML elements
Browser information
JavaScript-Specific Objects
Browser Object Model (BOM)
This code will create the object html_obj that points to the tag that
used the name/id "test".
Accessing Data from Forms
document.formname
document.forms["formname"]
Form Object Properties
action – Returns the URL address to which the form's data will be
submitted.
length – Returns the number of elements in the form.
method – Returns a string specifying data submission method, i.e.,
either 'get' or 'post'.
target – Returns the target window where the form's response will
appear.
Values include: self, parent, etc.
reset( ) – Resets the form to its default values. (Same result as
clicking the reset button.)
submit( ) – Submits the form's data. (Same result as clicking the
submit button.)
Form Element Object Properties
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(password.length<6){
alert("Password must be at least 6 characters
long.");
return false;
}
}
Example 2: Checking for '@' in E-mail
function emailcheck(email_string)
{
if(email_string.indexOf("@")==-1)
window.alert("Not a valid
email address!");
}
Example 2: Checking for '@' in E-mail
function validateEmail (emailAdress)
{
let regexEmail = /^\w+([\.-]?\w+)*@\w+([\.-
]?\w+)*(\.\w{2,3})+$/;
if (emailAdress.match(regexEmail)) {
return true;
} else {
return false;
}
}
}
Prepared by: Dr. Alimatu - Saadia Yussiff
</script>
84
</head>
Example3: Form Validation (Continue)
<body>
<h1> Address Information </h1> <br>
<form method=post enctype="text/plain" action=""
onSubmit="return verify(this);">