CH 4 - Working With JS Object
CH 4 - Working With JS Object
Chapter 4
JavaScript: Objects
Group: 6
3rd Year Sec D Students,
Dept. of Software Eng.
• Objects are more complex and each object may contain any combination of these primitive
data-types as well as reference data-types.
• An object, is a reference data type. Variables that are assigned a reference value are given a
reference or a pointer to that value. That reference or pointer points to the location in
memory where the object is stored. The variables don’t actually store the value.
};
This is the simplest and most popular way to create objects in JavaScript.
To create an object, use the new keyword with Object() constructor, like this:
person.firstName = 'testFirstName';
person.lastName = 'testLastName';
Internet Programming I Chapter 4 - JavaScript 8
Javascript Object creating
b) Using ‘new’ with user defined constructor function
problem with the approach of using the ‘Object’ constructor function result from the fact that
every time we create an object, we have to manually add the properties to the created object.so
we use user defined constructor.
And you want to create employees for this organization. Clearly, you want all the employee
objects.
console.log(employee.name); // "EmployeeOne"
Internet Programming I Chapter 4 - JavaScript 11
Javascript Object creating
4.Object.assign()
Object.assign method can take any number of objects as parameters. The first parameter is
the object that it will create and return. The rest of the objects passed to it will be used to copy
the properties into the new object. Let’s understand it by extending the previous example we
saw.
Now, you want an employee object of ‘ABC Corp’ who drives a ‘Ford’ car. You can do that with
the help of Object.assign as below:
Now, you get an employee object that has company and carName as its property.
Object Properties
In JavaScript, an object is a collection of properties, where each property is a key-value pair.
This Example creates a new object called person using an object initializer.
14
Object properties and methods
expression should evaluate to an object, and identifier is the name of the property you'd like to access.
A common way to access the property of an object is the dot property accessor
For example to access the firstName property of the person object, you use the following expression:
15
Object properties and methods cont…
You can use the dot property accessor in a chain to access deeper properties: object.prop1.prop2.
Choose the dot property accessor when the property name is known ahead of time.
The dot property accessor works correctly when the property name is a valid identifier.
16
Object properties and methods cont…
when a property name contains spaces, you need to place it inside quotes
17
Object properties and methods cont…
To access the properties with these special names, use the square brackets property accessor
The square brackets syntax accesses without problems the properties that have special names
Output:
19
Object properties and methods cont…
Output:
20
Object properties and
methods cont…
Object Methods
Objects have actions. The actions are represented by
functions. the following snippet adds the greet action to
the person object
21
Object properties and methods cont…
Output:
22
Object properties and methods cont…
23
Object properties and methods cont…
Data Properties
By default, the [[Configurable]], [[Enumerable]] and [[Writable]] attributes set to true
for all properties defined directly on an object. The default value of [[Value]] attribute is
undefined.
To change any attribute of a property you use the Object.defineProperty() method.
Object.defineProperty() method accepts three arguments:
● An object
● A property name of the object
● A property descriptor object that has four properties:
● Configurable
● Enumerable
● Writable
● Value
24
Object properties and methods cont…
Data Properties
Output
Output
25
Object Accessor Properties
properties and similar to data properties, accessor properties also have
methods [[Configurable]] and [[Enumerable]] attributes. But the accessor
properties have the [[Get]] and [[Set]] attributes instead of
cont… [[Value]] and [[Wirtable]].
26
Object properties and methods cont…
Accessor Properties
Output:
27
Object accessors
Output:
28
Object constructors and Prototype
➢ Object Constructor
● Instead of creating individual objects, what if we wanted to create several instance
objects from a single “Blueprint” object? This is when constructor functions come
into play.
● Constructor - is a function used to create instance objects with the new keyword.
● When you call a constructor, it will:
● create a new object
● bind this to the new object, so you can refer to this in your constructor
code
● run the code in the constructor
● return the new object.
age 25
24
introduceMySelf()
❖ We are creating an
“abebe” object from the
constructor “Person”
having the attributes
“name”, “age” and a
method
“intruduceMySelf”.
❖ Can you think of another
way of creating an
instance object from an
Object?
● When we create an object using function constructor, JavaScript Engine will add
dunder proto or __proto__ in the object which will point to the prototype’s constructor
object.
// function constructor
Output
const Person = function(name, job, yearOfBirth){
this.name= name;
this.job= job;
this.yearOfBirth= yearOfBirth;
}
Person.prototype.calculateAge= function(){
console.log('The current age is: '
+(2019- this.yearOfBirth));
}
console.log(Person.prototype);
TASK 1:
-Create a web page with two buttons “TakeOff” and “Land”, and an empty text field
area.
- Write an Airplane constructor that initializes `name` from an argument.
- All airplanes built with Airplane should initialize with an `isFlying` of false.
- Give airplanes the ability to `.takeOff()` and `.land()`:
+ If a plane takes off, its `isFlying` property is set to true.
+ If a plane lands, its `isFlying` property is set to false.
- When the takeOff button is clicked, “IsFlying = True” should be rendered to the
empty text area in the web page created.
- When the Land button is clicked, “IsFlying = False” should be rendered to the empty
text area in the web page created.
Internet Programming I Chapter 4 - JavaScript 36
Solution for Task 1
<!doctype html>
<html> TakeOff Land
<head><title>Lab Exercies</title></head>
<body>
<button id=”takeOffBtn”>TakeOff</button>
<button id=”landBtn”>Land</button>
<div id=”textField”></div>
<script src=”./app.js”></script> Text Area
</body>
</html>
37
Solution for Task 1
function Airplane(name) {
this.name = name;
this.isFlying = false;
}
Airplane.prototype.takeOff = function() {
this.isFlying = true;
};
Airplane.prototype.land = function() {
this.isFlying = false;
};
Airplane boing = new Airplane(“Boing”);
38
Solution for Task 1
39
Solution for Task 1
40
Practical Exercises
TASK 2
- Write a Person Constructor that initializes `name` and `age` from arguments.
- All instances of Person should initialize with an empty `stomach` array.
- Give instances of Person the ability to `.eat("someFood")`:
+ When eating an edible, it should be pushed into the `stomach`.
+ The `eat` method should have no effect if there are 10 items in the `stomach`.
- Give instances of Person the ability to `.poop()`:
+ When an instance poops, its `stomach` should empty.
- Give instances of Person a method `.toString()`:
+ It should return a string with `name` and `age`. Example: "Mary, 50"
TASK 3
- Create a web page with a form or you can use the register page from activity 4.
- Write a javascript program that creates an object and sets its values from the web
page form input.
- Render the object back to the web page.
}
const callBack = () => {
const newObject = new Register();
newObject.introduceMySelf()
}
document.getElementById('submitBtn').addEventListener('click', callBack);
44
Solution
Output
45
Inheritance and Prototype chain
● When it comes to inheritance, JavaScript only has one construct: objects. Each
object has a private property which holds a link to another object called its
prototype. That prototype object has a prototype of its own, and so on until an
object is reached with null as its prototype. By definition, null has no prototype,
and acts as the final link in this prototype chain.
function Person(firstName, lastName) ❖ Now any objects instantiated from the
{ “Person” constructor will inherit the
this.FirstName = firstName || "unknown";
properties and methods inside the
“Person” object.
this.LastName = lastName || "unknown";
❖ All objects are an instance of the “Object”
}; object. This is the last object in the
Person.prototype.getFullName = function () prototype chain before the Null prototype
{ return this.FirstName + " " + object. Therefore, all objects created in
this.LastName; } javascript inherit the methods and
properties pre-defined in the “Object”
object.
Internet Programming I Chapter 4 - JavaScript 46
Practical Exercises
1. Can an inherited method from the “Object” class be modified?
1. What do you think the output of the following code will be:
function Dog(name) {
this.name = name;
this.speak = function() {
return 'woof';
};
}
const dog = new Dog('Pogo');
Dog.prototype.speak = function() {
return 'arf';};
console.log(dog.speak());
Internet Programming I Chapter 4 - JavaScript 47
1. Traverse objects
➢ what it mean traverse objects?
▪ looping through objects .
▪ The various methods that can be used to loop through objects in JavaScript
are
⮚ Using a for...in loop
⮚ Object.keys method
⮚ Object.values method
The most straightforward way to loop through an object's properties is by using the for...in statement
function person (name,age){
this.name=name;
this.age=age;
}
var b=new person("Abebe",12);
for (const key in b) { // iterate over the user object
console.log(`${key}: ${b[key]}`);
}
// name: Abebe
// age: 12
this.age=age;}
person.prototype.bloodColor="red";
//if(person.hasOwnProperty(key);
console.log(`${key}: ${b[key]}`);
keys.forEach(function(index){
console.log(`${index}: ${Abebe[index]}`);
});
// output name: Abebe age: 12