JavaScript OOP Flashcards
What is OOP?
“Object-oriented programming (OOP) is a programming language model organized around objects rather than “actions”.”
OOP is a set of principles that we should follow if we want to use objects as the primary way of organizing our code.
Some of these principles are supported by language features
Others are more abstract principles we must follow when we write code
What are classes and why are they one of the fundamental OOP features in JS?
Classes are the fundamental language feature that allows us to use OOP
Classes are object templates that are used to model:
- State (using variables that we call fields)
- Behavior (using functions that we call methods)
What is the class state?
Fields are class data members
- They are the equivalent of variables
- They define the object state
Fields can have a default value
• This value will be applied to every object created from this class
What is class behavior?
Methods are class members that execute some action
- Just like a regular method that is part of an object
- Related fields and methods should be put in the same class
- Methods can interact with the fields
What are class instances and how can you create one?
Let’s take a look at this simplified Person class and how we can create objects (also known as an instance) from it
How can create instances with constructors?
Constructors are kind of special methods
- Invoked at the time of creating a new instance of an object
- Used to initialize the fields of the instance
What are static members and what are they used for?
The static keyword defines a static field or method for a class.
- Static members aren’t called on instances of the class.
- Instead, they’re called on the class itself.
- We use static fields when we want all instances to be able to access and/or modify.
- Static members are initialized just before the type is used for the first time
- There lifetime is the entire application lifetime
- Static members do not have access to this keyword
Static members are used when the type should have or do a specific thing that is not bound to any instance
Instance vs Static
Instance:
• Associated with an instance (object)•Initialized when the constructor is called•
Static:
• Associated with a type (class), not with an instance•Initialized just before the type is used for the first time•
What is the difference between OOP and FP?
• Functional programming - Organizing your code into multiple functions where each function works on its own
The advantage of the functional approach is that you have:
- A bunch of highly re-usable (and manageable) functions with little to no dependencies
- A very easy to maintain and understand code
- Object-oriented programming - Organizing your code in classes and objects (objects are based on classes)
Your data is stored in properties, and your logic in methods
• Data and logic that work closely together live in the same class