【问题标题】:what is upper scope of the child class?子类的上限范围是什么?
【发布时间】:2021-10-24 15:20:38
【问题描述】:

我了解到,根据您定义函数的位置,您可以确定函数的上限。(static scopelexical scope

例子

class Parent {
  constructor(name){
    this.name = name
  }
}

class Child extends Parent {

}


在这,

what is the upper scope of the Child class? is it Parent class or global?

我觉得……

因为子类是在全局中定义的,所以上层范围是全局的。但是,

根据原型链,似乎上层作用域是Parent Class。

我错过了什么?

【问题讨论】:

标签: javascript class inheritance prototype lexical-scope


【解决方案1】:

Child 类的上层范围是什么?是父类还是 全球?

这是全局范围。

因为子类是全局定义的,所以上层作用域是全局的

是的,没错。

根据原型链,似乎上层作用域是父类

原型不代表范围。你在这里比较苹果和橘子。

原型是用于为从特定构造函数创建的所有对象定义公共属性的对象。示例:所有数组实例共享Array.prototype 中定义的方法。

如果在对象中找不到特定属性,则遵循其原型链接并在该原型对象中查找该特定属性。

就作用域而言,如果在当前作用域中找不到特定标识符,则 Javascript 将在外部作用域中查找该标识符,在 Child 类的情况下是全局作用域.

示例

以下示例应该阐明范围和原型之间的区别:

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);
  • 在上面的代码示例中,在foo函数范围内,arr存在于本地范围内;如果没有,javascript 会在外部范围内寻找arr,即全局范围

  • 在下一行,标识符b,在函数foo的本地范围内不存在;因此,javascript 会在外部范围内寻找b,即全局范围

  • 方法forEach 将首先在arr 对象上查找。如果javascript在arr对象中找不到任何名为forEach的属性,则会在arr的原型中查找,即Array.prototype

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 2012-07-07
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多