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
Add a ment  | 

3 Answers 3

Reset to default 3

Replace 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