javascriptclassinheritanceprototypelexical-scope

what is upper scope of the child class?


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?


Solution

  • 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.

    Example

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