Learn to code with free online courses, programming projects, and interview preparation for developer jobs.
freeCodeCamp Object Oriented Programming Notes Part 1
I’m currently going through the new freeCodeCamp learning curriculum. I just finished the first part, which was the Responsive Web Design Certification course. Part of this course was to make responsive web design projects.
Check out the following articles for the notes I took while going through said course:
Flexbox Notes
CSS Grid Notes
Now that I’m done with the Responsive Web Design Certification course, the next course is the Javascript Algorithms And Data Structures Certification course. Check out this post for a list of all the notes I took while going through the first 5 parts of this course.
The sixth part of the JavaScript course is Basic Algorithm Scripting. Check out the notes I took while going through this course:
Part 1
Part 2
The seventh part of the JavaScript course is Object Oriented Programming. This is part 1 of the notes I took while going through said course.
At its core, software development solves a problem or achieves a result with computation. The software development process first defines a problem, then presents a solution. Object oriented programming is one of several major approaches to the software development process.
object oriented programming organizes code into object definitions. These are sometimes called classes, and they group together data with related behavior. The data is an object's attributes, and the behavior (or functions) are methods.
The object structure makes it flexible within a program. Objects can transfer information by calling and passing data to another object's methods. Also, new classes can receive, or inherit, all the features from a base or parent class. This helps to reduce repeated code.
Your choice of programming approach depends on a few factors. These include the type of problem, as well as how you want to structure your data and algorithms.
Create a Basic JavaScript Object
properties, define what makes up an object. Note that similar objects share the same properties, but may have different values for those properties. For example, all cars have wheels, but not all cars have the same number of wheels.
let owl = { name: "Hedwig", color: "white", owner: "Harry Potter", numLegs: 2 };
Use Dot Notation to Access the Properties of an Object
let mainCharacter = { name: "Harry Potter", age: 11, wizard: true, address: "4 Privet Drive", school: "Hogwarts School of Witchcraft and Wizardry" }; console.log(mainCharacter.name); //returns Harry Potter
Create a Method on an Object
let sirius = { name: "Sirius Black", wizard: true, pureblood: true, traitor: false, godson: "Harry Potter", brother: "Regulus Black", mother: "Walburga Black", father: "Orion Black", info: function() { return `${sirius.name} is the son of ${sirius.mother} and ${sirius.father}. He is the older brother of ${sirius.brother} and the godfather of ${sirius.godson}.`; } }; sirius.info(); //returns Sirius Black is the son of Walburga Black and Orion Black. He is the older brother of Regulus Black and the godfather of Harry Potter. console.log(sirius.info());
//object with method //function in method uses arrow functions var pansy = { firstName: "Pansy", lastName: "Parkinson", wizard: true, age: 11, house: "Slytherin", bloodStatus: "Pureblood", friends: ["Draco", "Daphne", "Blaise", "Theo"], info: () => `${pansy.firstName} ${pansy.lastName} is a ${pansy.house} ${pansy.bloodStatus} wizard.` }; console.log(pansy.info()); //returns Pansy Parkinson is a Slytherin Pureblood wizard.
Make Code More Reusable with the this Keyword
In the current context, this refers to the object that the method is associated with: duck.
If the object's name is changed to mallard, it is not necessary to find all the references to duck in the code. It makes the code reusable and easier to read.
let luna = { name: "Luna Lovegood", house: "Ravenclaw", friend: "Ginny Weasley", father: "Xenophilius Lovegood", info: function() { return `${this.name} is a ${this.house} student. Her father's name is ${this.father}. ${this.friend} is one of her friends.`; } }; console.log(luna.info()); //returns Luna Lovegood is a Ravenclaw student. Her father's name is Xenophilius Lovegood. Ginny Weasley is one of her friends.
Note: can’t use arrow functions with this keyword.
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
Refer to this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Define a Constructor Function
Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.
function Cat() { this.name = "Crookshanks"; this.color = "Ginger"; this.numLegs = 4; this.species = "Half-Kneazle"; this.owner = "Hermione Granger"; } let hermionesCat = new Cat();
function Auror() { this.headquarters = "Ministry of Magic", this.enemies = ["Voldemort", "Death Eaters"], this.description = "Aurors protect the Wizarding World from Dark Wizards." } let nymphadoraTonks = new Auror(); console.log(nymphadoraTonks.enemies); //returns (2) ["Voldemort", "Death Eaters"] let kingsleyShacklebolt = new Auror(); console.log(kingsleyShacklebolt.description); //returns Aurors protect the Wizarding World from Dark Wizards.
Extend Constructors to Receive Arguments
The constructor is more flexible. It's now possible to define the properties for each Bird at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.
function Pets(name, species, owner) { this.name = name; this.species = species; this.owner = owner; } let nevillesPet = new Pet("Trevor", "frog", "Neville Longbottom"); let harrysPet = new Pet("Hedwig", "owl", "Harry Potter"); let hermionesPet = new Pet("Crookshanks", "cat", "Hermione Granger"); let ronsPets = new Pet("Pigwidgeon", "owl", "Ron Weasley");
function Wand(owner, wood) { this.creator = "Ollivander", this.owner = owner, this.wood = wood, this.core = "Dragon Heartstring", this.info = function() { return `This ${this.core} wand is owned by ${this.owner}. It is made from ${this.wood} wood.` } } var minervasWand = new Wand("Minerva McGonagall", "fir"); console.log(minervasWand.info()); //returns This Dragon Heartstring wand is owned by Minerva McGonagall. It is made from fir wood. var luciusWand = new Wand("Lucius Malfoy", "elm"); console.log(luciusWand.wood); //returns elm console.log(luciusWand.core); //returns Dragon Heartstring console.log(luciusWand.info()); //returns This Dragon Heartstring wand is owned by Lucius Malfoy. It is made from elm wood.
Verify an Object's Constructor with instanceof
Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the instanceof operator. instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor. Here's an example:
let Wand = function(owner, wood, core) { this.owner = owner; this.wood = wood; this.core = core; this.maker = "Ollivander"; } let harrysWand = new Wand("Harry Potter", "holly", "Phoenix feather"); harrysWand instanceof Wand; let dracosWand = new Wand("Draco malfoy", "hawthorn", "Unicorn hair"); dracosWand instanceof Wand; let minervasWand = new Wand("Minerva McGonagall", "fir", "Dragon heartstring"); minervasWand instanceof Wand;
Understand Own Properties
function Teacher(name, subject) { this.name = name; this.subject = subject; this.school = "Hogwarts School of Witchcraft and Wizardry"; } let snape = new Teacher("Severus Snape", "Potions"); let snapeProperties = []; for (let property in snape) { if (snape.hasOwnProperty(property)) { snapeProperties.push(property); } } console.log(snapeProperties); //returns ["name", "subject", "school"]
Use Prototype Properties to Reduce Duplicate Code
function HPBook(title) { this.title = title; } HPBook.prototype.author = "J.K. Rowling"; let book1 = new HPBook("Harry Potter and the Philosopher's Stone"); console.log(book1.author); //returns J.K. Rowling let book2 = new HPBook("Harry Potter and the Chamber of Secrets"); console.log(book2.author); //returns J.K. Rowling
Iterate Over All Properties
Own properties are defined directly on the object instance itself. And prototype properties are defined on the prototype.
Add all of the own properties of beagle to the array ownProps. Add all of the prototype properties of Dog to the array prototypeProps.
function Dog(name) { this.name = name; } Dog.prototype.numLegs = 4; let beagle = new Dog("Snoopy"); let ownProps = []; let prototypeProps = []; for (let property in beagle) { if (beagle.hasOwnProperty(property)) { ownProps.push(property); } else { prototypeProps.push(property); } } console.log(ownProps); //returns ["name"] console.log(prototypeProps); //returns ["numLegs"]
function QuidditchMember(name, position) { this.name = name; this.position = position; } QuidditchMember.prototype.captain = "Oliver Wood"; QuidditchMember.prototype.team = "Gryffindor"; var fred = new QuidditchMember("Fred Weasley", "Beater"); var george = new QuidditchMember("George Weasley", "Beater"); var harry = new QuidditchMember("Harry Potter", "Seeker"); var ownProps = []; var prototypeProps = []; //using ternary operators instead of if-else statement for (let property in harry) { (harry.hasOwnProperty(property)) ? ownProps.push(property) : prototypeProps.push(property); } console.log(ownProps); //returns (2) ["name", "position"] console.log(prototypeProps); //returns (2) ["captain", "team"]
function DeathEater(name, house) {
this.name = name;
this.house = house;
}
DeathEater.prototype.leader = "Voldemort";
DeathEater.prototype.description = "Followers of Voldemort";
var peter = new DeathEater("Peter Pettigrew", "Gryffindor");
var lucius = new DeathEater("Lucius Malfoy", "Slytherin");
var ownProperty = [];
var prototypeProperty = [];
for (var property in peter) {
(peter.hasOwnProperty(property)) ? ownProperty.push(property) : prototypeProperty.push(property);
}
console.log(ownProperty);
//returns (2) ["name", "house"] console.log(prototypeProperty);
//returns (2) ["leader", "description"]
Understand the Constructor Property
Since the constructor property can be overwritten, it’s generally better to use the instanceof method to check the type of an object.
Write a joinDogFraternity function that takes a candidate parameter and, using the constructor property, return true if the candidate is a Dog, otherwise return false.
function Dog(name) { this.name = name; } function joinDogFraternity(candidate) { if (candidate.constructor === Dog) { return true; } else { return false; } }
function OrderMember(name) { this.name = name; } OrderMember.prototype.title = "Order of the Phoenix"; OrderMember.prototype.leader = "Albus Dumbledore"; OrderMember.prototype.symbol = "Phoenix"; var sirius = new OrderMember("Sirius Black"); function DeathEater(name) { this.name = name; } DeathEater.prototype.leader = "Voldemort"; var peter = new DeathEater("Peter Pettigrew"); //using arrow functions and ternary operators var joinOotP = (candidate) => (candidate.constructor === OrderMember) ? true : false; console.log(joinOotP(sirius)); //returns true console.log(joinOotP(peter)); //returns false var joinVoldemort = (candidate) => (candidate.constructor === DeathEater) ? true : false; console.log(joinVoldemort(sirius)); //returns false console.log(joinVoldemort(peter)); //returns true
Change the Prototype to a New Object
Add the property numLegs and the two methods eat()and describe()to the prototype of Dog by setting the prototype to a new object.
function Dog(name) { this.name = name; } Dog.prototype = { numLegs: 4, eat: function() { console.log("dog food"); }, describe: function() { console.log("Sirius Black's animagus form is a dog."); } };
function Hufflepuff(name) { this.name = name; } Hufflepuff.prototype = { houseName: "Hufflepuff", head: "Pomona Sprout", school: "Hogwarts", info: () => `Hufflepuff's head of house is Pomona Sprout, the Hogwarts Herbology teacher.` }; var susan = new Hufflepuff("Susan Bones"); console.log(susan.houseName); //returns Hufflepuff console.log(susan.info()); //returns Hufflepuff's head of house is Pomona Sprout, the Hogwarts Herbology teacher.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
2 ways to create an object in JavaScript
It's important to note that there are no classes(except in ES6) in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the classical languages.
Using Functions
Using Object literals
Using Functions
The most common way to create an object.First of we define a function to create an object of the class ( function ) by using new keyword.
If you want to add a behavior to your object, you can go for constructor and add methods to the object during construction or give your class a prototype.
If you don't have behavior associated with an object (i.e. if the object is just a container for data/state), I would use an object literal.
function myClass(foo,bar) {
this.foo = foo;
this.bar = bar;
// or:
myClass.prototype.verify = function () {
return this.foo === this.bar;
};
//creating object
var newInstance = new myClass(42,43);
// calling member function
newInstance. verify();
Using Object literals
If you don't need anything beyond a simple container of data, go with a simple literal.No behaviour associated with the object, we can go for object literals.The object created using Object literals are Singleton.