简体   繁体   English

静态方法中的访问构造函数var(es6)

[英]access constructor var in static method (es6)

Running into a situation where I have the following code: 遇到我有以下代码的情况:

class SomeClass{
    constructor(){
        let name="john doe"
    }

    static newName(){
        //i want to get the "name" variable here   
    }
}

In my console.log when i access newName() , I'm unable to get the reference of name variable which I understand, the class isn't instantiated when I call the static method. 在我的console.log中,当我访问newName() ,我无法获得我理解的name变量的引用,当我调用静态方法时,类没有被实例化。 So I guess my question is, what would be the best way for me to go about calling newName() and accessing the name variable? 所以我想我的问题是,对于我来说调用newName()和访问name变量的最佳方法是什么? I can create a variable above the class let name="john doe" and access it that way, but i'd like to figure out a way to keep everything confined in the class. 可以在类上面创建一个变量let name="john doe"并以这种方式访问​​它,但是我想找到一种方法来保持类中的所有内容。

First off, let's forget about the static for now. 首先,让我们暂时忘掉static So, your class should be like this: 所以,你的课应该是这样的:

class SomeClass {
  constructor() {
    this.name = "john doe";
  }

  newName() {
    return this.name;
  }
}

See the variable name ? 看变量name If you declare it with let (or var , or const ), it would be defined as local variable in the constructor . 如果用let (或varconst )声明它,它将在constructor定义为局部变量。 Thus, it can only be used inside the constructor method. 因此,它只能在constructor方法中使用。 Now, if you set it with the keyword this , it will be defined as an instance variable, therefore, it can be accessed throughout your class. 现在,如果使用关键字this设置它,它将被定义为实例变量,因此,可以在整个类中访问它。

Let's see now how you can instantiate your class and call the method newName : 现在让我们看看你如何实例化你的类并调用newName方法:

let someClass = new SomeClass(),
    name      = someClass.newName();

If you really want to use a static method, keep in mind that everything that happens inside it, is not attached to the instance of the object. 如果您确实想要使用静态方法,请记住,其中发生的所有内容都不会附加到对象的实例。

You can read more about es6 classes here . 您可以在此处阅读有关es6课程的更多信息。

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

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