SlideShare a Scribd company logo
JAVASCRIPT
OBJECTS,
CONSTRUCTORS,
PROPERTIES,
METHODS,
FUNCTIONS,
NOUNS AND VERBS TOGETHER
Let's go back to the analogy of computer
languages being like regular spoken
languages. In English, you have nouns
(which you can think of as "things") and
verbs (which you can think of as
"actions"). Until now, our nouns (data,
such as numbers, strings, or variables)
and verbs (functions) have been
separate.
No longer!
Using objects, we can put our
information and the functions that use
that information in the same place.
We've put an example of how objects can
be used

var phonebookEntry = {};
phonebookEntry.name = 'Oxnard
Montalvo';
phonebookEntry.number = '(555) 5555555';
phonebookEntry.phone = function() {
console.log('Calling ' + this.name + ' at ' +
this.number + '...');
};
phonebookEntry.phone();

OUTPUT
Calling Oxnard Montalvo at
(555) 555-5555...
OBJECTS SYNTAX
Did you see that? The phonebookEntry object handled data (a name and a telephone
number) as well as a procedure (the function that printed who it was calling).
In that example, we gave the key name the value 'Oxnard Montalvo' and the key
number the value '(555) 555-5555'. An object is like an array in this way, except its
keys can be variables and strings, not just numbers.
Objects are just collections of information (keys and values) between curly braces, like
this:
var myObject =
{
key: value,
key: value,
key: value
};
var me = {
name : "gitanjali",
age: 26
}
CREATING A NEW OBJECT
There are two ways to create an object: using object literal notation (which is what
you just did) and using the object constructor.
Literal notation is just creating an object with curly braces, like this:
var myObj =
{
type: 'fancy',
disposition: 'sunny'
};
var emptyObj = {};
When you use the constructor, the syntax looks like this:
var myObj = new Object();
This tells JavaScript: "I want you to make me a new thing, and I want that thing to be
an Object.
You can add keys to your object after you've created it in two ways:
myObj["name"] = "Charlie";
myObj.name = "Charlie";
Both are correct, and the second is shorthand for the first. See how this is sort of
similar to arrays?
Create your me object, but this time, use the object constructor. Once you make it,
use either the [] notation or the . notation to give it a name property with a string
value (your name) and an age property with a number value (your age).
var me = new Object();
me.name = "Gitanjali";
me["age"] = 26;
LETS MAKE FEW MORE OBJECTS
Create three objects called object1, object2, and object3 in the editor. Use either
literal notation or the object constructor, and give your objects any properties you
like!
var object1 ={
name: "Gitanjali",
age: 26,
complexion: "wheatish"
}

var object2 ={}
object2.name = "Mona";
object2.age = 26;
var object3 = new Object();
object3.name = "Gitanjali";
object3.age = 26;
CREATING YOUR OWN OBJECT
Create your own object called myOwnObject. Give it whatever properties you like! (Be
sure to give it at least one.) You can use either literal notation or the object
constructor.
var myOwnObject = {
interest: "playing",
outfit: "kurti",
name: "mona"
}
PROPERTIES
Each piece of information we include in an object is known as a property. Think of a
property like a category label that belongs to some object. When creating an object,
each property has a name, followed by : and then the value of that property. For
example, if we want Bob's object to show he is 34, we'd type in age: 34.
age is the property, and 34 is the value of this property. When we have more than one
property, they are separated by commas. The last property does not end with a
comma.
var Spencer = {
age: 22,
country: "United States"
};
var me = {
age: 26,
country: "India"
}
ACCESSING PROPERTIES
Now that we know how to make objects with properties, let's look at how we actually
use them! Notice our example objects bob and susan. In this case both bob and susan
each have two properties, name and age.
After creating our objects we have added code to access these properties. Notice that
we save bob's name, "Bob Smith", into the global variable name1.
var bob = {
name: "Bob Smith",
age: 30
};
var susan = {
name: "Susan Jordan",
age: 25
};
// here we save Bob's information
var name1 = bob.name;
var age1 = bob.age;
// finish this code by saving Susan's information
var name2 =susan.name;
var age2 =susan.age;
ANOTHER WAY TO CREATE
The method we've used to create objects uses object literal notation—that is,
creating a new object with { } and defining properties within the brackets.
Another way of creating objects without using the curly brackets { } is to use the
keyword new. This is known as creating an object using a constructor.
The new keyword creates an empty object when followed by Object(). The general
syntax is:
var objectName = new Object();
We then have to fill this object with properties and labels. How do we do that? Check
out the creation of the object bob to see what we do. We create the name property
for the object bob by using bob.name and assigning that to a value.
// Our bob object again, but made using a constructor this time
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// Here is susan1, in literal notation
var susan1 = {
name: "Susan Jordan",
age: 24
};
var susan2 = new Object();
susan2.name = "Susan Jordan";
susan2.age = 24;
See the below example using literal notation.
// help us make snoopy using literal notation
var snoopy ={
species:"beagle",
age: 10
};
// help make buddy using constructor notation
var buddy = new Object();
buddy.species = "golden retriever";
buddy.age = 5;
FUNCTION REVIEW
In this lesson we are going to focus on methods. Methods are an important part of
object oriented programming (OOP). OOP is an important part of programming which
we'll dive into later.
Methods are similar to functions. To prepare for methods, let's do a quick refresher on
functions.
Functions are defined using the function keyword followed by:
01. A pair of parentheses ( ) with optional parameters inside.
02. A pair of curly braces with the function's code inside { }.
03. A semicolon ;.
And when we call the function, we can put inputs (arguments) for the parameters.
For example, the square function on line 2 takes x as its parameter and returns that
parameter squared.
// Accepts a number x as input and returns its square
var square = function (x) {
return x * x;
};
Define the function multiply. It should take two parameters, x and y, and return the
product.
Then call your function, passing in any two arguments.
var multiply = function(x,y)
{
return x * y;
};
multiply(3,5);
SO WHATS METHOD?
In the last section, we discussed properties. We can think of properties as variables
associated with an object. Similarly, a method is just like a function associated with an
object.
Let's look at bob, our same person object from the last lesson. Instead of just having
the properties name and age , bob also has a method called setAge . As you can
probably guess, this method sets bob's age to whatever argument you give it.
Notice how we define setAge kind of like we define a property. The big difference is
that we put in a function after the equals sign instead of a string or number.
We call a method like a function, but we use ObjectName.methodName(). where we
use the method to change bob's age to 40. We did this by calling bob.setAge(40).
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// this time we have added a method, setAge
bob.setAge = function (newAge){
bob.age = newAge;
};
// here we set bob's age to 40
bob.setAge(20);
WHY METHODS ARE IMPORTANT?
Methods serve several important purposes when it comes to objects.
01. They can be used to change object property values. The method setAge allows us
to update bob.age.
02. They can be used to make calculations based on object properties. Functions can
only use parameters as an input, but methods can make calculations with object
properties. For example, we can calculate the year bob was born based on his age
with our getYearOfBirth method
var bob = new Object();
bob.age = 30;
bob.setAge = function (newAge){
bob.age = newAge;
};
bob.getYearOfBirth = function () {
return 2013 - bob.age;
};
console.log(bob.getYearOfBirth());
THE “ THIS” KEYWORD
It turns out we can make a method work for many objects using a new keyword, this.
The keyword this acts as a placeholder, and will refer to whichever object called that
method when the method is actually used.
Let's look at the method setAge to see how this works. By using the keyword this,
setAge will change the age property of any object that calls it. Previously, we had a
specific object bob instead of the keyword this. But that limited the use of the method
to just bob.
Then when we say bob.setAge = setAge, it means whenever we type bob.setAge( ),
this.age in the setAge method will refer to bob.age.

var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 50;
// and down here we just use the method we already made
bob.setAge = setAge;
bob.setAge(50);
MORE KINDS OF METHODS
Here we have an object square with a sideLength property to represent the length of
the square's side. This time, we have added a new method, calcPerimeter, which
computes the perimeter of the square. Notice we make use of the keyword return (in
the same way we use it in functions!).
var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
return this.sideLength * 4;
};
// help us define an area method here
square.calcArea = function(){
return this.sideLength * this.sideLength;
};
var p = square.calcPerimeter();
var a = square.calcArea();
CUSTOM CONSTRUCTORS
Approach of adding in properties one at a time for every object is tedious! Instead of
always using the boring Object constructor, we can make our own constructors.
This way we can set the properties for an object right when it is created. So instead of
using the Object constructor which is empty and has no properties, we can make our
own constructors which have properties.
Look at our Person constructor. This constructor is used to make Person objects.
Notice it uses the keyword this to define the name and age properties and set them
equal to the parameters given.
Now we can use this constructor to make our good friends bob and susan in only one
line each! Look at once we have the constructor, it's way easier to make people
because we can include their name and age as arguments to their respective
constructors.
function Person(name,age) {
this.name = name;
this.age = age;
}
// Let's make bob and susan again, using our constructor
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);
// help us make george, whose name is "George Washington" and age is 275
var george = new Person("George Washington", 275);
Lets look at our another example, we have made a Cat constructor for you, with age
and color properties.
function Cat(age, color) {
this.age = age;
this.color = color;
}
// make a Dog constructor here
function Dog(age,name,breed){
this.age = age;
this.name = name;
this.breed = breed;
}
This is much better than using the Object constructor
MORE OPTIONS
In a constructor, we don't have to define all the properties using parameters. Look at
our new Person example , and see how we set the species to be "Homo Sapiens" . This
means that when we create any Person, their species will be "Homo Sapiens". In this
way, the values associated with name and age are not yet assigned, but species will
always have the same value.
In this case, both sally and holden will have the same species of "Homo Sapiens",
which makes sense because that is the same across all people.
function Person(name,age) {
this.name = name;
this.age = age;
this.species = "Homo Sapiens";
}
var sally = new Person("Sally Bowles",39);
var holden = new Person("Holden Caulfield",16);
console.log("sally's age is " + sally.age + " and she is " );
console.log("holden's age is " + holden.age + " and he is " );
Ad

Recommended

Object properties
Object properties
sidneyodingo
 
Week 9 IUB c#
Week 9 IUB c#
Umar Farooq
 
Javascript
Javascript
baabtra.com - No. 1 supplier of quality freshers
 
EDMODO Integration Framework for Effective Teaching in Higher Education
EDMODO Integration Framework for Effective Teaching in Higher Education
Kiran Budhrani
 
Mumbaihikers upcoming treks december 2015
Mumbaihikers upcoming treks december 2015
Mumbai Hiker
 
Javascript
Javascript
poojanov04
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
divyapatel123440
 
Object oriented javascript
Object oriented javascript
Shah Jalal
 
Object oriented javascript
Object oriented javascript
Usman Mehmood
 
Javascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
chap09 - JavaScript Oheu4hir74huOJS.pptx
chap09 - JavaScript Oheu4hir74huOJS.pptx
MaxiAhiake
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
Object Oriented Javascript part2
Object Oriented Javascript part2
Usman Mehmood
 
Understanding-Objects-in-Javascript.pptx
Understanding-Objects-in-Javascript.pptx
MariaTrinidadTumanga
 
Object Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
11. session 11 functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
WEB222-lecture-4.pptx
WEB222-lecture-4.pptx
RohitSharma318779
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
OO in JavaScript
OO in JavaScript
Gunjan Kumar
 
JavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
Week3
Week3
Will Gaybrick
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object Oriented JavaScript
Object Oriented JavaScript
Julie Iskander
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 

More Related Content

Similar to Javascript Objects and Functions (20)

WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
divyapatel123440
 
Object oriented javascript
Object oriented javascript
Shah Jalal
 
Object oriented javascript
Object oriented javascript
Usman Mehmood
 
Javascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
chap09 - JavaScript Oheu4hir74huOJS.pptx
chap09 - JavaScript Oheu4hir74huOJS.pptx
MaxiAhiake
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
Object Oriented Javascript part2
Object Oriented Javascript part2
Usman Mehmood
 
Understanding-Objects-in-Javascript.pptx
Understanding-Objects-in-Javascript.pptx
MariaTrinidadTumanga
 
Object Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
11. session 11 functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
WEB222-lecture-4.pptx
WEB222-lecture-4.pptx
RohitSharma318779
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
OO in JavaScript
OO in JavaScript
Gunjan Kumar
 
JavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
Week3
Week3
Will Gaybrick
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object Oriented JavaScript
Object Oriented JavaScript
Julie Iskander
 
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
divyapatel123440
 
Object oriented javascript
Object oriented javascript
Shah Jalal
 
Object oriented javascript
Object oriented javascript
Usman Mehmood
 
Javascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
chap09 - JavaScript Oheu4hir74huOJS.pptx
chap09 - JavaScript Oheu4hir74huOJS.pptx
MaxiAhiake
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
Object Oriented Javascript part2
Object Oriented Javascript part2
Usman Mehmood
 
Understanding-Objects-in-Javascript.pptx
Understanding-Objects-in-Javascript.pptx
MariaTrinidadTumanga
 
Object Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
11. session 11 functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
JavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object Oriented JavaScript
Object Oriented JavaScript
Julie Iskander
 

Recently uploaded (20)

FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Ad

Javascript Objects and Functions

  • 2. NOUNS AND VERBS TOGETHER Let's go back to the analogy of computer languages being like regular spoken languages. In English, you have nouns (which you can think of as "things") and verbs (which you can think of as "actions"). Until now, our nouns (data, such as numbers, strings, or variables) and verbs (functions) have been separate. No longer! Using objects, we can put our information and the functions that use that information in the same place. We've put an example of how objects can be used var phonebookEntry = {}; phonebookEntry.name = 'Oxnard Montalvo'; phonebookEntry.number = '(555) 5555555'; phonebookEntry.phone = function() { console.log('Calling ' + this.name + ' at ' + this.number + '...'); }; phonebookEntry.phone(); OUTPUT Calling Oxnard Montalvo at (555) 555-5555...
  • 3. OBJECTS SYNTAX Did you see that? The phonebookEntry object handled data (a name and a telephone number) as well as a procedure (the function that printed who it was calling). In that example, we gave the key name the value 'Oxnard Montalvo' and the key number the value '(555) 555-5555'. An object is like an array in this way, except its keys can be variables and strings, not just numbers. Objects are just collections of information (keys and values) between curly braces, like this: var myObject = { key: value, key: value, key: value }; var me = { name : "gitanjali", age: 26 }
  • 4. CREATING A NEW OBJECT There are two ways to create an object: using object literal notation (which is what you just did) and using the object constructor. Literal notation is just creating an object with curly braces, like this: var myObj = { type: 'fancy', disposition: 'sunny' }; var emptyObj = {}; When you use the constructor, the syntax looks like this: var myObj = new Object(); This tells JavaScript: "I want you to make me a new thing, and I want that thing to be an Object.
  • 5. You can add keys to your object after you've created it in two ways: myObj["name"] = "Charlie"; myObj.name = "Charlie"; Both are correct, and the second is shorthand for the first. See how this is sort of similar to arrays? Create your me object, but this time, use the object constructor. Once you make it, use either the [] notation or the . notation to give it a name property with a string value (your name) and an age property with a number value (your age). var me = new Object(); me.name = "Gitanjali"; me["age"] = 26;
  • 6. LETS MAKE FEW MORE OBJECTS Create three objects called object1, object2, and object3 in the editor. Use either literal notation or the object constructor, and give your objects any properties you like! var object1 ={ name: "Gitanjali", age: 26, complexion: "wheatish" } var object2 ={} object2.name = "Mona"; object2.age = 26; var object3 = new Object(); object3.name = "Gitanjali"; object3.age = 26;
  • 7. CREATING YOUR OWN OBJECT Create your own object called myOwnObject. Give it whatever properties you like! (Be sure to give it at least one.) You can use either literal notation or the object constructor. var myOwnObject = { interest: "playing", outfit: "kurti", name: "mona" }
  • 8. PROPERTIES Each piece of information we include in an object is known as a property. Think of a property like a category label that belongs to some object. When creating an object, each property has a name, followed by : and then the value of that property. For example, if we want Bob's object to show he is 34, we'd type in age: 34. age is the property, and 34 is the value of this property. When we have more than one property, they are separated by commas. The last property does not end with a comma. var Spencer = { age: 22, country: "United States" }; var me = { age: 26, country: "India" }
  • 9. ACCESSING PROPERTIES Now that we know how to make objects with properties, let's look at how we actually use them! Notice our example objects bob and susan. In this case both bob and susan each have two properties, name and age. After creating our objects we have added code to access these properties. Notice that we save bob's name, "Bob Smith", into the global variable name1. var bob = { name: "Bob Smith", age: 30 }; var susan = { name: "Susan Jordan", age: 25 }; // here we save Bob's information var name1 = bob.name; var age1 = bob.age; // finish this code by saving Susan's information var name2 =susan.name; var age2 =susan.age;
  • 10. ANOTHER WAY TO CREATE The method we've used to create objects uses object literal notation—that is, creating a new object with { } and defining properties within the brackets. Another way of creating objects without using the curly brackets { } is to use the keyword new. This is known as creating an object using a constructor. The new keyword creates an empty object when followed by Object(). The general syntax is: var objectName = new Object(); We then have to fill this object with properties and labels. How do we do that? Check out the creation of the object bob to see what we do. We create the name property for the object bob by using bob.name and assigning that to a value. // Our bob object again, but made using a constructor this time var bob = new Object(); bob.name = "Bob Smith"; bob.age = 30;
  • 11. // Here is susan1, in literal notation var susan1 = { name: "Susan Jordan", age: 24 }; var susan2 = new Object(); susan2.name = "Susan Jordan"; susan2.age = 24; See the below example using literal notation. // help us make snoopy using literal notation var snoopy ={ species:"beagle", age: 10 }; // help make buddy using constructor notation var buddy = new Object(); buddy.species = "golden retriever"; buddy.age = 5;
  • 12. FUNCTION REVIEW In this lesson we are going to focus on methods. Methods are an important part of object oriented programming (OOP). OOP is an important part of programming which we'll dive into later. Methods are similar to functions. To prepare for methods, let's do a quick refresher on functions. Functions are defined using the function keyword followed by: 01. A pair of parentheses ( ) with optional parameters inside. 02. A pair of curly braces with the function's code inside { }. 03. A semicolon ;. And when we call the function, we can put inputs (arguments) for the parameters. For example, the square function on line 2 takes x as its parameter and returns that parameter squared. // Accepts a number x as input and returns its square var square = function (x) { return x * x; };
  • 13. Define the function multiply. It should take two parameters, x and y, and return the product. Then call your function, passing in any two arguments. var multiply = function(x,y) { return x * y; }; multiply(3,5);
  • 14. SO WHATS METHOD? In the last section, we discussed properties. We can think of properties as variables associated with an object. Similarly, a method is just like a function associated with an object. Let's look at bob, our same person object from the last lesson. Instead of just having the properties name and age , bob also has a method called setAge . As you can probably guess, this method sets bob's age to whatever argument you give it. Notice how we define setAge kind of like we define a property. The big difference is that we put in a function after the equals sign instead of a string or number.
  • 15. We call a method like a function, but we use ObjectName.methodName(). where we use the method to change bob's age to 40. We did this by calling bob.setAge(40). var bob = new Object(); bob.name = "Bob Smith"; bob.age = 30; // this time we have added a method, setAge bob.setAge = function (newAge){ bob.age = newAge; }; // here we set bob's age to 40 bob.setAge(20);
  • 16. WHY METHODS ARE IMPORTANT? Methods serve several important purposes when it comes to objects. 01. They can be used to change object property values. The method setAge allows us to update bob.age. 02. They can be used to make calculations based on object properties. Functions can only use parameters as an input, but methods can make calculations with object properties. For example, we can calculate the year bob was born based on his age with our getYearOfBirth method var bob = new Object(); bob.age = 30; bob.setAge = function (newAge){ bob.age = newAge; }; bob.getYearOfBirth = function () { return 2013 - bob.age; }; console.log(bob.getYearOfBirth());
  • 17. THE “ THIS” KEYWORD It turns out we can make a method work for many objects using a new keyword, this. The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used. Let's look at the method setAge to see how this works. By using the keyword this, setAge will change the age property of any object that calls it. Previously, we had a specific object bob instead of the keyword this. But that limited the use of the method to just bob. Then when we say bob.setAge = setAge, it means whenever we type bob.setAge( ), this.age in the setAge method will refer to bob.age. var setAge = function (newAge) { this.age = newAge; }; var bob = new Object(); bob.age = 50; // and down here we just use the method we already made bob.setAge = setAge; bob.setAge(50);
  • 18. MORE KINDS OF METHODS Here we have an object square with a sideLength property to represent the length of the square's side. This time, we have added a new method, calcPerimeter, which computes the perimeter of the square. Notice we make use of the keyword return (in the same way we use it in functions!). var square = new Object(); square.sideLength = 6; square.calcPerimeter = function() { return this.sideLength * 4; }; // help us define an area method here square.calcArea = function(){ return this.sideLength * this.sideLength; }; var p = square.calcPerimeter(); var a = square.calcArea();
  • 19. CUSTOM CONSTRUCTORS Approach of adding in properties one at a time for every object is tedious! Instead of always using the boring Object constructor, we can make our own constructors. This way we can set the properties for an object right when it is created. So instead of using the Object constructor which is empty and has no properties, we can make our own constructors which have properties. Look at our Person constructor. This constructor is used to make Person objects. Notice it uses the keyword this to define the name and age properties and set them equal to the parameters given. Now we can use this constructor to make our good friends bob and susan in only one line each! Look at once we have the constructor, it's way easier to make people because we can include their name and age as arguments to their respective constructors. function Person(name,age) { this.name = name; this.age = age; }
  • 20. // Let's make bob and susan again, using our constructor var bob = new Person("Bob Smith", 30); var susan = new Person("Susan Jordan", 25); // help us make george, whose name is "George Washington" and age is 275 var george = new Person("George Washington", 275); Lets look at our another example, we have made a Cat constructor for you, with age and color properties. function Cat(age, color) { this.age = age; this.color = color; } // make a Dog constructor here function Dog(age,name,breed){ this.age = age; this.name = name; this.breed = breed; } This is much better than using the Object constructor
  • 21. MORE OPTIONS In a constructor, we don't have to define all the properties using parameters. Look at our new Person example , and see how we set the species to be "Homo Sapiens" . This means that when we create any Person, their species will be "Homo Sapiens". In this way, the values associated with name and age are not yet assigned, but species will always have the same value. In this case, both sally and holden will have the same species of "Homo Sapiens", which makes sense because that is the same across all people. function Person(name,age) { this.name = name; this.age = age; this.species = "Homo Sapiens"; } var sally = new Person("Sally Bowles",39); var holden = new Person("Holden Caulfield",16); console.log("sally's age is " + sally.age + " and she is " ); console.log("holden's age is " + holden.age + " and he is " );

Editor's Notes