javascript - 为什么 people[1].a 无权访问 User 类的属性?
问题描述
为什么 people[1].a 无法访问 User 类的属性,但需要通过proto嵌套?!
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
static a = 12;
}
class User2 extends User {}
let people = [
new User2('Vasia', 20),
new User2('Peter', 19),
new User2('Misha', 21),
]
console.dir(User2.a) // 12
console.dir(people[1].a) // ?????
解决方案
static
属性出现在 Class 对象上。它们不会出现在类的实例上。
它们旨在保存静态方法。
来自MDN:
static 关键字定义类的静态方法。不会在类的实例上调用静态方法。相反,它们是在类本身上调用的。这些通常是实用函数,例如创建或克隆对象的函数。
推荐阅读
- python - 从文本文件中的单词中去除特定的标点符号
- postgresql - 从具有相同行数的联合选择表中加入 2 个别名表
- c# - 如何在 Azure 中列出经典虚拟机
- sql - TOAD ORA-01821: 日期格式无法识别
- android - 安卓工作室 | NEGOTIATE 身份验证错误:提供的名称无效(机制级别:KrbException:找不到默认领域)
- python-3.x - 未找到 PYD 文件
- python - 如何在不重命名图像的情况下解决此问题。ValueError: int() 以 10 为底的无效文字:'1 (1)'
- html - 仅带空格的输入字段不允许以角度保存?
- r - R从分组数据框到桑基图
- javascript - 将 django 变量传递给 javascript