Read Chapters 1b and pages 106 - 117
Let's break down those words by first reviewing objects.
What is an object? An object stores a lot of info about a thing.
What kind of info does an object have? It has keys and values.
Give an example of an object below.
//Type here
Objects form the basis of object oriented JavaScript.
Up to this point in time, we have explored how objects contain data, properties, and/or variables. We will build on this foundation.
In this unit, we will explore:
JavaScript is not really an object-oriented language (it is so much more!), but it has properties that helps it to operate like one. Objects are still critically important.
We've reviewed the word "object" in Object Oriented JavaScript. Now let's take a closer look at JavaScript!
JavaScript is a high-level, interpreted programming language. It is a programming language that is characterized as weakly typed, and prototype-based.
JavaScript supports event-driven, functional, and imperative (including object-oriented and prototype-based) programming styles.
High-Level
Interpreted
Weakly-typed
var x;
You do in other languages! In Swift, for example: var x: String
var x = "Laura"
and then later, you can run x = 3
. You have changed the type, but JavaScript does not mind!Event-driven
Object-Oriented and Prototype-based
In summary, JavaScript is:
In other words, JavaScript is awesome and multi-purpose!
Watch these Object Oriented JavaScript videos.
Software is a collection of cooperating objects rather than a collection of functions or simply a list of commands.
Takeaway: Software is made up of objects that have properties and methods to handle state and behavior.
Objects are great because they contain DATA and FUNCTIONALITY.
As programmers, we like to control both data and functionality!
Based on the previous slide, let's create a radio object together that handles both DATA and FUNCTIONALITY.
//radio object example demo
//properties: madeOfMetal, hasButtons, usesBatteries
//methods: playMusic, displayTime, connectBluetooth
Feel free to use JSBin, if more room is needed.
//Example of an object with properties
var dice = {
sides: 6,
color: "green"
};
Now how do we add functionality (or methods) to objects?
Adding functionality to objects means adding functions.
Functions that are attached to objects are called methods.
So let's review functions by examining the function below.
//This is an example of a function. Please explain each line of code.
function diceRoll() {
var sides = 6;
var randomNumber = Math.floor(Math.random() * sides) + 1;
console.log(randomNumber);
}
On the next slide, we will take this function, drop its name, attach it to a key, and make it into a method in our object.
Ta-da! The function declaration on the previous page has been transformed into a method here.
var dice = {
roll: function() {
var sides = 6;
var randomNumber = Math.floor(Math.random() * sides) + 1;
console.log(randomNumber);
}
};
How do you access the key of roll in this dice object?
Yes, use dot notation!
Now run dice.roll in the console. What do you notice?
So how do we execute the function? What syntax do we need? Let's confirm on the next slide.
Given this same object from the previous slide...
var dice = {
roll: function() {
var sides = 6;
var randomNumber = Math.floor(Math.random() * sides) + 1;
console.log(randomNumber);
}
};
Now run dice.roll() in the console.
What do you notice?
Now let's make sides a property of the dice object instead of a variable in the function, therefore changing the variable's scope. How would we refactor the code?
var dice = {
roll: function() {
var sides = 6;
var randomNumber = Math.floor(Math.random() * sides) + 1;
console.log(randomNumber);
}
};
After refactoring the code, how will you update the function so that the method runs properly?
What is the benefit of having sides as a property
of the dice object?
var dice = {
sides: 6,
roll: function() {
var randomNumber = Math.floor(Math.random() * dice.sides) + 1;
console.log(randomNumber);
}
};
Now we can easily change the value of the property sides in our code to accommodate all kinds of dice!
How do you update the dice object to have 10 sides? dice.sides = 10;
Sometimes, we want to share methods between objects.
Examples in daily life:
Sometimes, we want to share methods between objects.
For example, we want a toaster oven that combines the best methods of both worlds: the toaster and the oven.
var toaster = {
slots: 2,
time: 3,
toast: function() {
console.log("Ready to toast for " + toaster.time + " minutes.");
}
};
var oven = {
slots: 2,
time: 20,
bake: function() {
console.log("Ready to bake for " + oven.time + " minutes.");
}
};
Imagine an app that has 200 user objects. What are some basic features common to apps?
Wouldn't it be nice if addProfilePic, addTagline, postUpdate, likePost, etc. methods can be used by these 200 objects?
Now imagine each object containing each of the above methods, which means A LOT of repetitive lines of code!
On the next slide we will begin to solve this problem.
Functions can access the variables that are located locally within their scope.
So far, we have talked about
Now we are going to talk about
JavaScript has an extremely powerful keyword - "this
".
this
can be used to access data contextually, allowing your functions and methods to access the data that they need based on execution context.this
keyword can be used to access values, methods, and other objects on a context-specific basis.
this
can change based on where it is used.
this
always points to the object that it has been linked to.
var circle = {
radius: 2,
circumference: function() {
return Math.PI * 2 * this.radius;
}
}
console.log(circle.circumference()); // 12.566370614359172
//'this' is referring to 'circle' object.
Let's make another object that has a bigger radius.
var biggerCircle = {
radius: 4
};
Using dot notation, how do we create a circumference method for this bigger circle object? See next slide. 😊
var biggerCircle = {
radius: 4
};
biggerCircle.circumference = circle.circumference;
Let's console.log the circumference of the bigger circle.
console.log(biggerCircle.circumference()); // 25.132741228718345
//What is happening above?
The this
in the circumference method is now referencing the radius of the bigger circle object!
this
allows one function (method) to operate on many states (instances).
var portland = {
name: "Portland",
bridges: 12,
airport: 1,
soccerTeams: 1,
logNumberOfBridges: function () {
console.log ("There are " + this.bridges + " bridges in " + this.name);
}
}
portland.logNumberOfBridges();
this
is an identifier that gets a value bound to it, much like a variable. Ex: this
.property
, .call(this, param)
Instead of identifying the values explicitly in your code block, this
gets bound to the correct object automatically.
this
is so helpful for methods.
Think of this
as a pronoun.
var person = {
firstName: "Penelope",
lastName: "Barrymore",
getName: function () {
return this.firstName + " " + this.lastName;
}
}
console.log(person.getName());
var myDog = {
username: 'coach',
age: '1'
}
Let's create an object constructor based on this object literal:
var myDog = {
username: 'coach',
age: '1'
}
Because constructor functions are functions that when called create new instances of an object, what keyword will we use to create one? function
function
Let's create an object constructor based on this object literal:
var myDog = {
username: 'coach',
age: '1'
}
Constructor functions must have names in capital case (first letter of each word capitalized).
To create instances that are all dogs, what word is best to name this function? Dog
function Dog() {
}
Let's create an object constructor based on this object literal:
var myDog = {
username: 'coach',
age: '1'
}
Because we want our constructor function to have 2 properties (username and age), what must we pass into the constructor function?
function Dog(username, age) {
}
Let's create an object constructor based on this object literal:
var myDog = {
username: 'coach',
age: '1'
}
Constructor functions create objects (has properties, values).
So after passing parameters into the function, in its code we need info about the instances' properties and values.
function Dog(username, age) {
propertyName1 = username; //value of username stored in a property name
propertyName2 = age; //value of age stored in a property name
}
Let's create an object constructor based on this object literal:
var myDog = {
username: 'coach',
age: '1'
}
Values will change based on what is passed into the function.
However, property names stay the same.
The this keyword is useful for running functions contextually.
So we use this before the dot notation to insert properties for instances of Dog.
function Dog(username, age) {
this.username = username;
this.age = age;
}
var myDog = {
username: 'coach',
age: '1'
}
In order to call the Dog function to give us an instance of Dog (instantiate) that looks like the above object literal, we must use the keyword new.
After the keyword, we will call the Dog function, passing in the values of "coach" and "1" respectively.
We will store this information into a variable called myDog.
function Dog(username, age) {
this.username = username;
this.age = age;
}
var myDog = new Dog('coach', '1');
Subsequent instantiations can now be made with one line of code!
function Dog(username, age) {
this.username = username;
this.age = age;
}
var myDog = new Dog('coach', '1');
Instantiate and store the information in a variable called yourDog.
var yourDog = new Dog('archie', '2');
Next slide: A recap on object literals and object constructors.
Object Literal
var flower = {
color : "red",
petals : 32,
smellsPretty : true
};
Constructor Object
function Flower(color, petals, smell){
this.color = color;
this.petals = petals;
this.smellsPretty = smell;
}
var myNewFlower = new Flower('red', 32, true);
Creating a user-defined object requires two steps:
function
that utilizes this
in its code block.new
.Example:
//Defines the new object
function Contact(name, email) {
this.name = name;
this.email = email;
}
//Creates the new instance
var myContact = new Contact('Laura', 'laura@hello.com');
Important: the name of the function is capitalized so you know it is a constructor!
What would the name value be in myContact?
console.log(myContact.name);
What would the name value be in myOtherContact?
function Contact(name, email) {
this.name = name;
this.email = email;
}
//Creates the new instance
var myOtherContact = new Contact('Hubs', 'hubs@hello.com');
console.log(myOtherContact.name);
var myContact = new Contact('Laura', 'laura@hello.com');
Can you think of other specific times when you would need to use an object constructor?
this
to that object.prototype
property to be the constructor function's prototype
object.Given the following code:
function Animal(species, noise) {
this.species = species;
this.noise = noise;
this.makeNoise = function() {
console.log(this.noise + ", " + this.noise);
}
}
How would you create an instance of an Animal?
How would you describe a task in a todo list. Your task should have:
function TodoListItem(description) {
this.description = description;
this.isDone = false;
this.markAsComplete = function() {
this.isDone = true;
}
}
var task = new TodoListItem("Do the laundry!");
What kind of objects you might need for your new Social Media site?
What would be the properties on those objects?
If we run this code over and over again (to create new instances):
function City (name, nickname) {
this.name = name;
this.nickname = nickname;
this.slogan = function () {
console.log(this.name + " is the best city in the country!");
};
}
var sanFrancisco = new City("San Francisco", "City By The Bay");
Every time we create an object, the program runs the code, and a new anonymous function is created again and again.
More code in your program means more space used in the computer’s memory.
How do we solve this problem?
We can add a method onto this object constructor by using prototype
.
function City(name, nickname) {
this.name = name;
this.nickname = nickname;
}
City.prototype.slogan = function(){
console.log(this.name + " is the best city in the country!");
}
var sanFrancisco = new City("San Francisco", "City By The Bay");
sanFrancisco.slogan();
function Circle(radius) {
this.radius = radius;
}
Circle.prototype.circumference = function() {
return Math.PI * 2 * this.radius;
}
Circle.prototype.area = function() {
return Math.PI * this.radius * this.radius;
}
var circle = new Circle(2);
circle.radius; // this is 2; it's stored on the circle
circle.area; // this is a function; it's stored on Circle.prototype
circle.area(); // this is a function call; inside it, "this" points to the circle
A constructor function makes an object linked to its own prototype
function Greeter(who) {
this.me = who;
}
Greeter.prototype.identify = function (){
return "I am " + this.me;
};
var person1 = new Greeter("Alice");
var person2 = new Greeter("Bob");
person1.constructor === Greeter; //true
person1.constructor === person2.constructor; //true
Let's explore the code in Codepen.
CodePen is similar to JS Bin in that it hosts a
read, evaluate, print loop (REPL) environment for our code.
Familiarize yourself with CodePen by reviewing these instructions.
The Animal Constructor inherits properties/methods of the Global Object. The Dog Constructor extends the Animal Constructor. Lassie is an instance of the Dog Constructor. Lassie inherits properties/methods of both Constructors: Animal, Dog.
function Greeter(who) {
this.me = who;
}
Greeter.prototype.identify = function() {
return "I am " + this.me;
};
Greeter.prototype.speak = function() {
alert("Hello, " + this.identify() + ".");
};
var person1 = new Greeter("Alice");
person1.speak():
this
can be thought of as "dynamic scope" (as opposed to lexical scope like global and local scope)this
tells us which building to go into, or which address of the building downtown to go intoprototype
tells us how we are going to find properties if they don't exist on the direct objectGo to FreeCodeCamp.
Sign in with your Github account.
Complete the first 8 lessons (including instanceof).
Check out this Codepen.
The object constructor will need .call()
to handle the properties.
The prototype of the object constructor will need Object.create()
to handle the methods.
Let's review the documentation.
Notice that this
needs to passed into .call()
with the property name of another object constructor.
function Greeter(who) {
this.me = who;
}
Greeter.prototype.identify = function(){
return "I am " + this.me;
}
//.call() with "this" and a property of Greeter passed in
//will allow Bar to access Greeter's "who" property.
function Bar(who) {
Greeter.call(this,who);
}
Let's review the documentation.
Notice the prototype
of an object constructor is passed into Object.create()
to handle methods of another object constructor.
Object.create(Greeter.prototype);
The function's execution is assigned to the prototype
of another object constructor:
Bar.prototype = Object.create(Greeter.prototype);
The Bar Constructor can now have a method that uses Greeter's "identify" method.
alert("Hello, " + this.identify() + ".");
Assigning the above code block to a method of Bar Constructor's prototype
allows instances of Bar to access methods of Bar and Greeter.
Bar.prototype.speak = function (){
alert("Hello, " + this.identify() + ".");
}
How do we make instances of Bar (e.g., customers)?
function Greeter(who) {
this.me = who;
}
Greeter.prototype.identify = function(){
return "I am " + this.me;
}
function Bar(who) {
Greeter.call(this,who);
}
Hint: Bar accepts one parameter.
var customer1 = new Bar("Viola");
var customer2 = new Bar("Jamie");
The Bar Constructor has a speak method. How do you call it for customer1?
customer1.speak();
What do we expect to see when we run the last line of code?
function Greeter(who) {
this.me = who;
}
Greeter.prototype.identify = function(){
return "I am " + this.me;
}
function Bar(who) {
Greeter.call(this,who);
}
Bar.prototype = Object.create(Greeter.prototype);
Bar.prototype.speak = function (){
alert("Hello, " + this.identity() + ".");
}
var customer1 = new Bar("Viola");
var customer2 = new Bar("Jamie");
customer1.speak();
prototype
to extend Greeter's prototype
so that Bar can link to Greeter's methods.We've been looking at prototype and inheritance. Let's explore the following code and explain line by line.
// The constructor function
function Paperback(title, author, numPages, cover) {
Book.call(this, title, author, numPages);
this.cover = cover;
}
// Extending the Book object
Paperback.prototype = Object.create(Book.prototype);
// A new method on this object
Paperback.prototype.burn = function() {
console.log("Omg, you burnt all " + this.numPages + " pages");
this.numPages = 0;
}
// Instantiating a new object
var paperback = new Paperback("1984", "George Orwell", 250, "cover.jpg");
paperback.read();
paperback.burn();
Let's revisit Codepen.
Click here and do in Visual Studio Code
Thank you for your attention!