admin管理员组文章数量:1404604
I have class in ES6 like this:
class temp
{
name = "";
type = 0;
required = true;
range = false;
default = "";
...
...
}
the temp class has many property, i can't give all of them in constructor.
How to create list of temp class like :
let list = [
new Input(name="test1", type=0, ...),
new Input(required=true, default="d", ...),
new Input(type=1, default="s", ...),
new Input(name="test2", default="s", ...)
]
I have class in ES6 like this:
class temp
{
name = "";
type = 0;
required = true;
range = false;
default = "";
...
...
}
the temp class has many property, i can't give all of them in constructor.
How to create list of temp class like :
let list = [
new Input(name="test1", type=0, ...),
new Input(required=true, default="d", ...),
new Input(type=1, default="s", ...),
new Input(name="test2", default="s", ...)
]
Share
Improve this question
edited Dec 24, 2018 at 16:51
Morteza
asked Dec 24, 2018 at 16:22
MortezaMorteza
1916 silver badges14 bronze badges
1
- 2 Time to study some tutorials on using javascript classes – charlietfl Commented Dec 24, 2018 at 16:36
3 Answers
Reset to default 3Replace your class with this one:
class Input {
construtor(name, type, required, range) {
this.name = name;
this.type = type;
this.required = required;
this.range = range;
}
}
Whatever you want to initialize in your class, use constructor
.
If you put them outside of the constructor OR function it will throw an error.
Don't use default
as a variable because it is a reserved key in JavaScript.
Also if you see your class name (temp
) it is different from the name mentioned in the list (Input
). Replace it.
To set the properties, add a constructor method that takes the property values as arguments to your class and then within that constructor method, you can set the class properties
constructor(x, y) {
this.x = x;
this.y = y;
}
Firstly in your class, you need a constructor if you want to be able to instantiate it with certain properties
class temp{
constructor(name = "", type, required = "true", range="false", tdefault = ""){
this.name = name;
this.type = type;
this.required = required;
this.range = range;
this.tdefault = tdefault;
}
}
Then you can construct them anonymously in the array
let list = [
new temp("test1", 0, true, false, "d"),
etc,
etc
]
btw the = "true" and other stuff in the constructor is the ES6 way of giving things a default value.
本文标签: ecmascript 6How to set property of class in Javascript ES6Stack Overflow
版权声明:本文标题:ecmascript 6 - How to set property of class in Javascript ES6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744828647a2627213.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论