Introduction to OOP Flashcards
(38 cards)
How does OOP structure a problem compared to procedural programming?
OOP is a programming paradigm that organizes a problem in terms of objects and how they interact with each other.
Any OO problem will have many possible approaches. In choosing an approach for OOP, there will always be tradeoffs. There is never one absolutely correct solution.
Procedural programming solves a problem in a series of steps that are performed one after the other.
What are some advantages and disadvantages of OOP?
Advantages:
- OOP models objects by using real-world nouns to represent objects, making it easier to think about a problem at a higher-level of abstraction.
- OOP reduces the amount of dependencies throughout a large, complex program.
- OOP code is easier to maintain since it is more flexible and easy to understand.
Disadvantages:
- Often longer programs
- Possibly less efficient code, requiring more memory or computing power
Describe the concept of encapsulation.
Encapsulation is the idea of bundling state (data) and behavior (operations) to form a single entity (e.g. an object).
In its broader sense, encapsulation also refers to restricting the access to an object’s state and behaviors.
Objects reveal a public interface when interacting with other objects but keeps their implementation details hidden so their data cannot be easily manipulated. An object should only expose the methods and properties that other objects need to use.
Unfortunately, JS doesn’t support access restrictions. There are ways to achieve a degree of access restriction, but they’re not perfect.
What is the compact method syntax?
Emission of the colon : and the ‘function’ keyword. A parenthesis is used to denote a method.
Example ‘drive’ method uses compact method syntax:
let raceCar = { make: 'BMW', fuelLevel: 0.5, engineOn: false,
startEngine: function() {
this.engineOn = true;
},
drive() {
this.fuelLevel -= 0.1;
},
}
What are collaborators in OOP?
An object or primitive value that is used to store state within another object.
Collaborators represent the connections between various actors in a program therefore playing an important role in modeling complicated problems.
They are at the core of OOP since they allow the problem to be chopped up and modularized into smaller pieces.
Example, ‘cat’ object is a collaborator of ‘pete’ object. We can use pete.pet to call makeNoise().
let cat = { name: 'Fluffy',
makeNoise() {
console.log(‘Meow! Meow!’);
},
};
let pete = {
name: ‘Pete’,
pet: cat,
printName() {
console.log(My name is ${this.name}!
);
console.log(My pet's name is ${this.pet.name}
);
},
};
What are object factories aka factory functions?
Functions that create and return objects of a particular type (e.g. race cars).
It is a way to automate object creation and reduce code duplication.
The methods remain the same across the objects, while the property values can be customized by providing them as arguments.
What are ways to iterate over an object’s properties? What are the differences between the methods?
- for/in loop iterates over an object’s properties, including properties from its prototype chain. Use ‘hasOwnProperty’ to skip the prototype properties.
- Object.keys returns an object’s “own” property keys, excluding properties from its prototype chain.
Both methods deal with enumerable properties, which are properties you can iterate over.
What is a prototype chain? How does it work?
A prototype chain are all inherited prototypes of an object.
For example, if an object ‘b’ inherited from object ‘a’ and an object ‘c’ inherits from object ‘b’, then both object ‘a’ and ‘b’ are part of the prototype chain of object ‘c’.
let a = { foo: 1 }; let b = { bar: 2 }; let c = { baz: 3 };
Object.setPrototypeOf(c, b);
Object.setPrototypeOf(b, a);
console. log(c.bar); // => 2
console. log(c.foo); // => 1
What is the _ _ proto _ _ property?
The dunder proto property is a deprecated, non-hidden version of the [[Prototype]] property.
As a rule, you should only use __proto__ if you need to support very old browsers or old versions of Node.
What are ‘bare’ objects?
‘Bare’ objects are objects without Object.prototype at the end of its prototype chain. You can create a ‘bare’ object by using ‘Object.create(null)’.
‘Bare’ objects won’t have access to usual object methods like .hasOwnProperty.
To check if an object is a ‘bare’ object:
if (Object.getPrototypeOf(obj) && obj.isPrototypeOf(car)) { // obj has a non-null prototype AND // obj is in the prototype chain of car }
Describe the concept prototypal inheritance.
The idea that JavaScript objects can inherit properties and behaviors from other objects.
Prototype is the object that another object inherits properties and methods from (i.e. parent object).
How does the Object.create method work?
Object.create takes a prototype object as an argument and returns a new object with inherited properties.
The new object will not have any properties or methods of its own. The new object’s [[Prototype]] property is assigned to the original prototype object.
Example:
let a = { foo: 1, bar: 2} let b = Object.create(a) console.log(b.foo) // => 1 console.log(b) // => { } (empty object)
What are the functions of Object.getPrototypeOf and Object.setPrototypeOf?
Object.getPrototypeOf() returns the prototype object of the passed in object.
Object.setPrototypeOf() takes in two arguments. First is the prototype object to inherit and second is the object you would like to set the prototype property.
Why are prototype properties considered references?
Prototype properties are references, so changing the ORIGINAL prototype object will also mutate the inherited object’s prototype properties.
What are higher-order functions?
Higher-order functions are functions that either:
- Return another function
- Takes another function as an argument
Examples of functions that takes a function as an argument: array methods - map, filter, forEach, reduce
What is the global object in JS?
JavaScript creates a global object when it starts running. The global object serves as the implicit execution context and is avaialble everyone in the program.
Whenever a value is assigned to a variable without using ‘let’, ‘const’, or ‘var’, the variable will be assigned to the global object.
In Node.js, the global object’s name is ‘global’. In the browser, the name is ‘window’.
Example of global properties: isNaN, parseInt
What are the steps to approaching an OOP?
- Write a textual description of problem
- Extract all SIGNIFICANT nouns and verbs from description
- Organize and associate the verbs and nouns
What are constructors?
Constructors are functions that work as a factory and can create an endless number of objects of the same type.
Constructor functions:
- Always begin with a capital letter
- Called with the ‘new’ keyword
- Uses ‘this’ to set the object’s properties and methods
- Cannot be an arrow function (due to arrow functions’ surrounding context issues)
- Don’t supply an explicit return value
What happens when an explicit return value is supplied in a constructor function?
If a primitive value is returned, it will be ignored. However, is the return value is an object, then the ‘new’ keyword will return the provided object instead of a new object.
Describe the usage of the ‘instanceof’ operator.
The ‘instanceof’ operator determines whether a given constructor created an object
E.g.
> corolla instanceof Car
‘instanceof’ requires the object on the right of the operator to have a ‘prototype’ property (i.e. be a constructor function)
In the example above, ‘Car’ must be a constructor or a class for ‘instanceof’ to work.
What is a constructor function’s prototype property?
Constructor functions contain a special ‘prototype’ property called the Function Prototype, which differs from the Object prototype (though the two are closely related concepts)
E.g.
> Car.prototype // => Car {};
When you call a constructor function with the ‘new’ keyword, JS sets the new object’s [[Prototype]] property to equal the constructor function’s ‘prototype’ property.
I.e Car.prototype = new object’s [[Prototype]] property.
Every object that the constructor creates inherits from the constructor’s prototype property.
The ‘prototype’ property is available in every JS function, but is only used when you call the function using the ‘new’ keyword.
What happens when you call a constructor function with the ‘new’ keyword?
Hint: 5 Steps
- Creates an entirely new object
- Sets the constructor’s prototype property as the [[Prototype]] for the new object
- Sets the execution context (or the value of ‘this’) for the methods to point to the new object
- Invokes the function
- Returns the new object (unless the function has a return value of another object)
Describe the OLOO pattern.
Object Linking Other Objects is another way to create objects in bulk.
It has one significant advantage over factory functions in that it uses less memory because all common properties and methods of the same object type are extracted to a prototype object.
First you create a prototype object that contains all common methods.
> let carPrototype = { > start() { > this.engineOn = true; > }, > > init(make, model) { > this.make = make; > this.model = model; > this.engineOn = false; > return this; // important to return execution context > } > }
It is also common to use an ‘init()’ method to initialize and customize the properties that are specific to each instance.
Then we can use Object.create method to create a new object and pass in the prototype object just created as its [[Prototype]] property.
> let corolla = Object.create(carPrototype).init(‘Toyota’, ‘Corolla);
What are ES6 classes? How do they differ from other object creation methods?
Classes provide a cleaner, more compact way to write constructors and prototypes.
They act like ‘syntactic sugar’ to make it easier for programmers familiar with other OOP languages to migrate to JavaScript.
Classes are considered functions when using the ‘typeof’ operator.
e.g. > Class Dog { > constructor(name, species) { > this.name = name; > this.species = species; > } > bark() { > console.log('Woof!') > } > } > let maxi = new Dog('maxi', 'terrier');