gpt4 book ai didi

javascript - JavaScript 中的类属性

转载 作者:行者123 更新时间:2023-12-03 16:27:42 25 4
gpt4 key购买 nike

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

   class Person {}

我们想添加一个属性。我们如何做到这一点?根据我的阅读,有两种方法:
  class Person {myProperty ='Something'} //As shown at https://javascript.info/class. If we use console.log(Person) the property will not show

现在让我们创建另一个扩展 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);
}
}

现在让我们使用 Athlete 作为构造函数创建一个新对象
const athlete = new Athlete();
console.log(athlete)// It will have the property myProperty with value 'Something else'

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

  • 谢谢,

    埃兰维

    最佳答案

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

    基于documentation :

    Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.



    因此,根据链接中的建议,您的代码用于声明类实例的公共(public)属性:
    class Person {
    myProperty ='Something' // this means anyone can access the property
    }

    对于私有(private)属性,他们建议使用以下语法:
    class Person {
    #myPrivateProperty ='Something' // this means only the instance methods have access
    }

    要回答您的问题:

    1. Where is myProperty stored, I can't find it anywhere inside Person or Athlete?


    它被存储为 Person 实例的实例属性。类(class)。由于 Athlete扩展它, Athlete 的一个实例也将被赋予相同的属性。阅读 Object Oriented Programming更多细节。

    1. Why can I access myProperty inside writeSomething()?

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

    1. Why does myProperty appear inside athlete, when it didn't appear anywhere else?


    它应该出现在 Person 中实例也是如此。例如,您可以编写:
    const person = new Person();
    person.myProperty = 'new Something';

    1. Is this another way of writing properties as opposed to Person.myProperty or is it something else?


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

    最后,如果你想 声明一个类属性 ,您需要将其指定为 static像这样的属性(property):

    class Person {
    static myProperty = 'some value';
    }
    console.log(Person.myProperty);

    关于javascript - JavaScript 中的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60099396/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com