I learned that depending on where you defined the function, you determine the upper scope of the function.( static scope
or lexical scope
)
example
class Parent {
constructor(name){
this.name = name
}
}
class Child extends Parent {
}
in this,
what is the upper scope of the Child class? is it Parent class or global?
I think...
because Child class is defined in global, upper scope is global. but,
According to prototype chain, it seems that upper scope is Parent Class.
What am I missing?
what is the upper scope of the Child class? is it Parent class or global?
It's the global scope.
because Child class is defined in global, upper scope is global
Yes, exactly.
According to prototype chain, it seems that upper scope is Parent Class
Prototypes do not represent the scope. You are comparing apples and oranges here.
Prototypes are objects that are used to define common properties for all objects that are created from a particular constructor function. Example: all array instances share methods defined in Array.prototype
.
If a particular property can't be found in an object, its prototype link is followed and that particular property is looked-up in that prototype object.
As far a scope is concerned, if a particular identifier can't be found in the current scope, then Javascript will look for that identifier in the outer scope, which in the case of the Child
class is the global scope.
Following example should clarify the different between scope and the prototype:
function foo(arr) {
// ".forEach" method will be looked-up in the "Array.prototype"
arr.forEach(n => console.log(n));
// "b" will be searched for in the outer scope, i.e. global scope
console.log(b);
}
const numArr = [1, 2, 3];
foo(numArr);
In the above code example, inside the foo
function scope, arr
exists in the local scope; if it didn't, javascript would have looked for arr
in the outer scope, i.e. the global scope
On the next line, identifier b
, does not exist in the local scope of function foo
; as a result, javascript will look for b
in the outer scope, i.e. the global scope
The method forEach
will be first looked-up on the arr
object. If javascript can't find any property named forEach
in the arr
object, it will be looked up in the prototype of arr
, i.e. the Array.prototype