Introduction to OOP Flashcards

1
Q

How does OOP structure a problem compared to procedural programming?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are some advantages and disadvantages of OOP?

A

Advantages:

  1. 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.
  2. OOP reduces the amount of dependencies throughout a large, complex program.
  3. OOP code is easier to maintain since it is more flexible and easy to understand.

Disadvantages:

  1. Often longer programs
  2. Possibly less efficient code, requiring more memory or computing power
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe the concept of encapsulation.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the compact method syntax?

A

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;
},
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are collaborators in OOP?

A

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});
},
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are object factories aka factory functions?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are ways to iterate over an object’s properties? What are the differences between the methods?

A
  1. for/in loop iterates over an object’s properties, including properties from its prototype chain. Use ‘hasOwnProperty’ to skip the prototype properties.
  2. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a prototype chain? How does it work?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the _ _ proto _ _ property?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are ‘bare’ objects?

A

‘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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Describe the concept prototypal inheritance.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does the Object.create method work?

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the functions of Object.getPrototypeOf and Object.setPrototypeOf?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why are prototype properties considered references?

A

Prototype properties are references, so changing the ORIGINAL prototype object will also mutate the inherited object’s prototype properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are higher-order functions?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the global object in JS?

A

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

17
Q

What are the steps to approaching an OOP?

A
  1. Write a textual description of problem
  2. Extract all SIGNIFICANT nouns and verbs from description
  3. Organize and associate the verbs and nouns
18
Q

What are constructors?

A

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
19
Q

What happens when an explicit return value is supplied in a constructor function?

A

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.

20
Q

Describe the usage of the ‘instanceof’ operator.

A

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.

21
Q

What is a constructor function’s prototype property?

A

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.

22
Q

What happens when you call a constructor function with the ‘new’ keyword?

Hint: 5 Steps

A
  1. Creates an entirely new object
  2. Sets the constructor’s prototype property as the [[Prototype]] for the new object
  3. Sets the execution context (or the value of ‘this’) for the methods to point to the new object
  4. Invokes the function
  5. Returns the new object (unless the function has a return value of another object)
23
Q

Describe the OLOO pattern.

A

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);

24
Q

What are ES6 classes? How do they differ from other object creation methods?

A

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');
25
Q

What are first-class functions?

A

All JavaScript functions are first-class functions, which means they act like any other value in JS and can:

  • Be assigned to variables and properties
  • Passed to other functions
  • Returned from another function
26
Q

What are the differences between function declarations and function expressions?

A

Function definitions that begin with the ‘function’ keyword are function declarations. All else are function expressions.

JS runs programs in 2 passes; the first pass performs hoisting and the second executes the code.

Hoisting involves scanning a program for function declarations before the code is executed. Therefore it is possible to invoke function declarations before it occurs in the code.

Function expressions are not hoisted, so the function must be invoked after the expression appears in the code.

27
Q

Describe the two concepts - the object prototype and the [[Prototype]] (dunder proto) property.

A

An object prototype is the object that a new object inherits properties and methods from. (Think of a parent object)

E.g. Object.create method creates a new object that inherits properties from its argument - the prototype object.

Newly created objects will have access to all properties and methods in the prototype object. i.e. The new object DELEGATES property and method access to its prototype object.

All JavaScript objects have an internal [[Prototype]] property (dunder proto) to keep track of its prototype object.

E.g. When a new object is created with Object.create, the new object’s [[Prototype]] property is assigned to the prototype object.

The [[Prototype]] property can be accessed using Object.getPrototypeOf().

28
Q

How does the prototype chain work in JS?

A

All JavaScript objects can inherit from another object using the [[Prototype]] property.

Since the prototype of an object is an object itself, the prototype object can also have a prototype from which it inherits.

  1. When you try to access an object’s property or method using the dot notation or bracket notation, it will first look in the object’s own properties.
  2. If there is no such property is will look in the object’s prototype object.
  3. If it still doesn’t exist, it will look in the object’s prototype’s prototype and so on until it reaches the end of the chain, which is equal to null.
  4. If no property is found at the end, the property access will equal ‘undefined’.
Example:
> let a = {apple: 1};
> let b = {banana: 2};
> let c = {cherry: 3};

> Object.setPrototypeOf(b, a);
Object.setPrototypeOf(c, b);

c.apple // => 1;

The prototype chain looks a like:

c –> b –> a –> Object.prototype –> null

29
Q

How does the ‘constructor’ method work?

A

The ‘constructor’ property is a property within a constructor function’s ‘prototype’ property. The method uses that property to identify the original constructor of an instance.

If a function’s ‘prototype’ property is changed (e.g. using Object.create) then the ‘constructor’ property must change back to point to the function or else the ‘constructor’ method will not work.

Example
 > function Person(name) {
 >    this.name = name;
 > }
 > function Child (name, school) {
 >    Person.call(this, name);
 >    this.school = school;
 > }
 > Child.prototype = Object.create(Person.prototype);    
 > Child.prototype["constructor"] = Child;
30
Q

What is the difference between an object prototype and a function prototype?

A

An object prototype is an object in which another object can inherit properties and methods from. All objects in JavaScript uses an internal [[Prototype]] property to keep track of their prototype object.

A function prototype is a special property that is available to all function-form objects. Constructor functions uses this ‘prototype’ property to store properties and methods available to its instances. When a constructor function is called with the ‘new’ keyword, a new object is returned and its internal [[Prototype]] property is set to point to constructor function’s ‘prototype’ property.

In most cases, when people talk about a prototype without being explicit, they mean an object prototype.

31
Q

What are instance properties/methods and static properties/methods? What are their differences?

A

Instance properties belong to the instances of a specific type. They are created by a constructor or class and are stored in either the instance object or in the constructor’s prototype property.

Static properties belong to the constructor or class itself. They do not apply to a specific instance created by that constructor. Static methods and properties are more general and relevant to all objects of the same type.

32
Q

What is an execution context? How is an execution context determined?

A

An execution context is the environment in which a function executes. It is also the value of the ‘this’ keyword.

HOW you invoke a function determines the execution context for that invocation. i.e. Two invocations of the same function can have very different contexts depending on how the calls are made

The implicit execution context for method invocations is the object used to call the method.

> let foo = {
>    bar: function() {
>        console.log(this)
>    }
> }
> foo.bar()     // => logs 'foo'

However, if you assign the method to another variable and then call it, the execution context will change:

> let baz = foo.bar
> baz();      // => logs 'Object[global]'

The implicit execution context for functions is the global object (as noted above) except when using strict mode, which will be ‘undefined’.

33
Q

What are 3 ways to explicitly set an execution context?

A
1. call() method can be used to set context for methods and functions
> function logName() {
>     console.log(this.name);
> }
> let bob = {name: 'Bob' }
> logName.call(bob);    // => logs 'Bob'
  1. apply() method can also be used to set context. The difference is that it accepts an array as arguments to the function or method. apply() is handy when you have a list of arguments ready in an array.
    > function add(num1, num2, num3) {
    > return this.age + num1 + num2 + num3;
    > }
    > let bob = { this.age = 23 };
    > let arrayNum = [24, 50, 60];
    > add.apply(bob, arrayNum);
  2. bind() method permanently binds a function or method to an execution context. bind() returns a new function and does not call the function or method itself. The execution context cannot be undone or reset after it is bound.
34
Q

What are the 3 possible scenarios in context loss? What are the possible solutions to the 3 scenarios?

A
  1. Copying method from object
    => Pass the context as an argument to the new function and use the call() method to invoke the original function
    => Use the bind() method when passing or copying the function to another function
  2. Inner function not using surrounding context
    => Preserve context by creating a variable in the outer scope and set it equal to ‘this’ Then call the inner function using the variable as the context.
    => Call the inner function with an explicit context using the call() or apply() methods
    => Permanently bind the inner function to the context of the outer function
    => Use an arrow function (MOST COMMON)
  3. Function as an argument loses its surrounding context
    => Preserve context with a variable in outer scope
    => Use bind
    => Use an arrow function
    => Use the optional ‘thisArg’ argument available for some methods that allows an optional argument specifying the context to use when invoking a function
35
Q

What is the difference between a method invocation and a function invocation?

A

A method invocation calls a function definition within an object and usually has the object set as its execution context.

A function invocation calls a function and usually has the global object set as its execution context.

36
Q

What are the two types of inheritance? What are each of its key features?

A
  1. Prototypal inheritance aka object inheritance is when an object’s internal [[Prototype]] property points to another object, delegating method calls to that other object.
    Example: OLOO pattern uses prototypal inheritance to link objects.
> const animal = {
>     
  1. Pseudo-classical inheritance aka constructor inheritance is when a constructor’s prototype inherits from another constructor’s prototype property.
    i. e. when a sub-type inherits from a super-type

When people talk about inheritance in the context of JavaScript they generally refer to this type of constructor inheritance.

37
Q

What type of inheritance does JavaScript support?

A

JavaScript only supports single inheritance in that objects can only inherit from one object and classes can only extend one other class.

Other OOP languages allow for multiple inheritance.

Inheritance works well when one object type is positively in a ‘is a’ relationship. I.e. a sub-type fully embodies a supertype

E.g. Penguin is a swimming bird and embodies all properties and behaviors of a swimming bird

38
Q

What are JS mix-ins? How are they used?

A

JavaScript mix-ins is a pattern that copies methods and properties from one object to another object using Object.assign.

A mix-in is an object that has one or more methods that can be mixed into a class.

This grants the class access to all methods in the object.

E.g. There are animals that can swim, animals that can fly, and animals that can do both.

> const Swim = { swim () }
> const Fly = { fly() }
> class Animal { }
> class Penguin extends Animal { }
> Object.assign(Penguin.prototype, Swim);
> class Turtle extends Animal { }
> Object.assign(Turtle.prototype, Swim);