Advanced JS Flashcards
What type of scoping rule(s) does Javascript have?
Lexical
one floor up in scope until you hit the global vs. dynamic - call stack
What exceptions or cheats are used with the kind of scoping rule(s) JavaScript has?
eval
and wait
What are the different ways you can create a new scope?
Functions, catch
block, (block scope) {} with let
What’s the difference between undeclared and undefined?
Undefined was declared but never initialized, undeclared was never declared, doesn’t exist in any scope. Undefined is a value, but a variable that is undefined does not currently have a value.
What determines which object a function’s this
points to? What’s the default?
In order of precedence
-
new
keyword - Explicit Binding:
.call()
or.apply()
/ hard binding - Implicit Binding: Owning or containing object (obj.function call)
- Default: global unless strict mode is on and then it is undefined
How do you “borrow” a function by implicit assignment of this
?
When you call the function in the context of an object - mutate the object to put a reference of the function on that object.
How do you explicitly bind this
?
.call()
or .apply()
How can you seal a specific object to a function? Why do that? Why not?
.bind()
- to be predictable for the this
binding, but you loose flexibility.
How do you create a new this
object?
By using the new
keyword
What is a closure and how is it created?
Function that remembers and accesses its lexical scope even when it is executed outside of its lexical scope. It is created when an inner function is transported out of the outer function.
How long does its scope stay around?
As long as there is some function that has a closure to a scope it will stay, but as soon as they all go away the scope will go away.
Why doesn’t a function callback inside a loop behave as expected? How do we fix it?
Because it shares a scope since the variable is not created per iteration so when the value changes it will give whatever value is present at the time of execution. We fix it by wrapping it in an IIFE or use let.
How do you use a closure to create an encapsulated module? What are the benefits of that approach?
Has to have an outer-wrapping function and return one or more inner functions that have a closure over the scope. Benefit: public API, encapsulation, least privilage.
Tradeoff - modules hide/make inner functions hard or impossible to test.
Tradeoff: New modules creates a whole bunch of extra copies
What is a constructor?
A function called with the new keyword in front of it.
What is [[Prototype]] and where does it come from?
Linkage from one object to another object - can get from Object.create or from the new keyword.