JavaScript 中的类属性

ela*_*nvi 5 javascript prototype class

我有一个关于类属性的问题。我将创建一个示例以更好地理解。假设我们有一堂课。

   class Person {}
Run Code Online (Sandbox Code Playgroud)

我们想添加一个属性。我们该怎么做呢?根据我的阅读,有两种方法:

  class Person {myProperty ='Something'} //As shown at https://javascript.info/class. If we use console.log(Person) the property will not show
Run Code Online (Sandbox Code Playgroud)

现在让我们创建另一个扩展 Person 的类,假设 Athlete 和我想更改 myProperty:

  class Athlete extends Person{// If we use console.log(Athlete.myProperty ) it will show undefined
       myProperty='Something else'// it changes the property

        writeSomething() {
            console.log(this.myProperty);
        }
   }
Run Code Online (Sandbox Code Playgroud)

现在让我们使用 Athlete 作为构造函数创建一个新对象

const athlete = new Athlete();
console.log(athlete)// It will have the property myProperty with value 'Something else'
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. myProperty 存储在哪里,我在 Person 或 Athlete 中找不到它?
  2. 为什么我可以在 writeSomething() 中访问 myProperty?
  3. 为什么 myProperty 出现在运动员内部,而没有出现在其他任何地方?
  4. 这是与 Person.myProperty 相反的另一种编写属性的方式还是别的什么?

谢谢你,

埃兰维

tec*_*yle 3

首先,它们不是“类属性”。它们是刚刚预先声明的实例属性。这使您清楚地了解类实例中可以期望哪些字段(属性)。

根据文档

公共和私有字段声明是JavaScript 标准委员会 TC39 提出的一个实验性功能(第 3 阶段) 。浏览器的支持是有限的,但可以通过 Babel 等系统的构建步骤来使用该功能。

因此,根据链接中的建议,您的代码用于声明类实例的公共属性:

class Person {
  myProperty ='Something' // this means anyone can access the property
}
Run Code Online (Sandbox Code Playgroud)

对于私有属性,他们建议使用以下语法:

class Person {
  #myPrivateProperty ='Something' // this means only the instance methods have access
}
Run Code Online (Sandbox Code Playgroud)

回答您的问题:

  1. myProperty 存储在哪里,我在 Person 或 Athlete 中找不到它?

它存储为类实例的实例属性Person。由于Athlete扩展了它,Athlete所以也将被赋予相同的属性。阅读面向对象编程了解更多详细信息。

  1. 为什么我可以在 writeSomething() 中访问 myProperty?

writeSomething()是实例的方法,因此它可以访问任何实例属性。(公立私立)

  1. 为什么 myProperty 出现在运动员内部,而没有出现在其他任何地方?

Person它也应该出现在实例中。例如,你可以写:

const person = new Person();
person.myProperty = 'new Something';
Run Code Online (Sandbox Code Playgroud)
  1. 这是与 Person.myProperty 相反的另一种编写属性的方式还是别的什么?

它只是使实例属性的声明变得更容易、更直观,并且带有隐式访问修饰符(即public)。


最后,如果你想声明一个类属性,你需要将其指定为static如下所示的属性:

class Person {
  myProperty ='Something' // this means anyone can access the property
}
Run Code Online (Sandbox Code Playgroud)