在静态方法(es6)中访问构造函数var [英] access constructor var in static method (es6)
问题描述
遇到以下代码的情况:
class SomeClass{
constructor(){
let name="john doe"
}
static newName(){
//i want to get the "name" variable here
}
}
在我访问newName()
时,在console.log中,无法获取我理解的name
变量的引用,调用静态方法时不会实例化该类.所以我想我的问题是,对我来说,调用newName()
并访问name
变量的最佳方法是什么?我可以在类let name="john doe"
上方创建一个变量并以这种方式访问它,但我想找出一种将所有内容限制在该类中的方法.
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. So I guess my question is, what would be the best way for me to go about calling newName()
and accessing the name
variable? 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.
推荐答案
首先,让我们暂时忘记static
.因此,您的课程应该是这样的:
First off, let's forget about the static
for now. So, your class should be like this:
class SomeClass {
constructor() {
this.name = "john doe";
}
newName() {
return this.name;
}
}
看到变量name
吗?如果使用let
(或var
或const
)声明它,则它将在constructor
中定义为局部变量.因此,它只能在constructor
方法内部使用.现在,如果使用关键字this
进行设置,它将被定义为实例变量,因此可以在整个类中对其进行访问.
See the variable name
? If you declare it with let
(or var
, or const
), it would be defined as local variable in the constructor
. Thus, it can only be used inside the constructor
method. 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.
现在让我们看看如何实例化您的类并调用方法newName
:
Let's see now how you can instantiate your class and call the method 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.
您可以在此处阅读更多有关es6类的信息. .
这篇关于在静态方法(es6)中访问构造函数var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!