简体   繁体   中英

JavaScript class definition without instanciation

I'd like to define an empty data class in JS to fill it with JSON afterwards. In c# I'd do something like that :

class Person {
    string name;
    int age;
    Person[] children;
    var whatever;
}

This doesn't work, the IDE doesn't like it : "Unexpected token. A constructor, method, accessor, or property was expected".

I've tried

class Person {
    var name;
    var age;
    var children;
    var whatever;
}

but I have no experience with JS, and everywhere I see that declared variables are defined right away.

I don't understand the error since I believe those are properties, and I don't know the behaviour of the JSON deserializer regarding arrays of objects, knowing said objects might be missing properties in the JSON but I'd still want them to be declared (but not set) in the JS object created from the string.

How can I make things work ?

You would need to make it an object rather than a class, and then fill the properties in when you receive your JSON.

You should use something like:

var Person = {
    name: '',
    age: '',
    children: '',
    whatever: ''
}

You can then access the properties of the Person object with Person.name etc.

Deserializing will be as simple as

Person = FunctionThatGivesYouAPersonObjectInJSON();

JSON is the notation used for Java Script objects, so you don't need to store these variables in a class. Just store it in a normal object. If you are reciving a JSON object from ajax request for example you can store it as a normal variable.

So just use that object.

You define a class of this way.

class Person{
 constructor(name, age, children, whatever) {
  this._name = name;
  this._age = age;
  this._children = children;
  this._whatever = whatever;
  }
}

To instantiate, you do this.

var chris = new Person('Chris', 25, 2, 1)

In ECMAScript6 you can implement Classes with JavaScript: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

So you will have to change your code to:

class Person{
  constructor(age, name) {
    this.age = age;
    this.name = name;
  }
}

Also, problem might be in your IDE settings. Usually in IDE you can select which language version you would like to use. For Example in WebStorm you can select in Settings:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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