简体   繁体   English

Javascript - Class - 调用构造函数属性时返回未定义的方法

[英]Javascript - Class - Method Returning Undefined When Calling Constructor Property

I'm currently learning Javascript.我目前正在学习 Javascript。 When I run the following code, I am getting undefined.当我运行以下代码时,我变得不确定。 Not sure what is wrong.不知道出了什么问题。 Everything seems to be fine.一切似乎都很好。 Any help will be appreciated.任何帮助将不胜感激。 Thank you.谢谢你。

class User{
  constructor(){
    this.array = [1, 2, 3]
  }

  static getNumber(){
    return console.log(this.array)
    
  }
}


User.getNumber()

First of all, you have to create a new instance of User with new User() or new User if you want to be able to access instance properties (such as array ), because they are created with this.array =... .首先,如果您希望能够访问实例属性(例如array ),则必须使用new User()new User创建一个新的User实例,因为它们是使用this.array =...创建的。 From the Mozilla Web Docs:来自 Mozilla Web 文档:

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. static 方法和 static 属性都不能在 class 的实例上调用。 Instead, they're called on the class itself.相反,它们在 class 本身上被调用。

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. Static 方法通常是实用函数,例如创建或克隆对象的函数,而 static 属性对于缓存、固定配置或您不需要跨实例复制的任何其他数据很有用。

Because getNumber is called on the constructor itself, it doesn't have access to any of the instance properties (the only one is this.array ).因为getNumber是在构造函数本身上调用的,所以它无法访问任何实例属性(唯一的一个是this.array )。 When new User is called, it creates the this.array , but only for the instance, not the constructor.调用new User时,它会创建this.array ,但仅用于实例,而不是构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM