2 Pillars: Closures & Prototypal Inheritance Flashcards
What are some reasons that functions might be considered first class citizens in JavaScript?
- Functions can return functions
- Functions can be stored in data structures
- Functions can be passed as arguments to other functions
What is a closure, and how/why would you use one?
a closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
Why would you use one?
Hiding of information that is unnecessary to be seen by the outside world or manipulated
Main benefits of closures of data encapsulation b/c some data not directly exposed
Explain how prototypal inheritance works*
This is an extremely common JavaScript interview question. All JavaScript objects have a prototype property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object’s prototype, and the prototype’s prototype and so on, until it finds the property defined on one of the prototypes or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance.
Why is the prototype inheritance useful?
- You can have objects pointing to the same place in memory, it’s more efficient
- can easily make copies
What are the 4 Pillars of OOP?
- Encapsulation - wrap code into boxes that are related to one another so they can interact w/ each other. More maintainable & reusable.
- Abstraction - hiding the complexity from the user, creating simpler interfaces
- Inheritance - ‘favorite’ party of OOP
- Polymorphism - many forms. Ability to call the same method are diff objects & each object responds in diff ways. Customize methods. Don’t need to copy & paste, reuse functionality.