首页 > 解决方案 > 为什么 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) // ?????

标签: javascriptclassprototypeproto

解决方案


static属性出现在 Class 对象上。它们不会出现在类的实例上。

它们旨在保存静态方法。

来自MDN

static 关键字定义类的静态方法。不会在类的实例上调用静态方法。相反,它们是在类本身上调用的。这些通常是实用函数,例如创建或克隆对象的函数。


推荐阅读