How can I do this in javascript? (Adding getters and setters properly)
public class User {
private UUID uuid;
private String nickName;
private double coins;
private int level;
private float exp;
public User(UUID uuid) {
this.uuid = uuid;
this.nickName = null;
this.coins = 0D;
this.level = 1;
this.exp = 0F;
}
}
In JavaScript you don't need to create first a class to create an object. A Javascript object is an associative array that can contain also functions:
// example of JavaScript object
const user = {
uuid: "user-identifier",
nickname: null,
// ...
}
Of course you can define a function that returns an object. You can think at that function as a constructor if you want, but it is just a function that returns an object. Function closures allow you to define private variables.
function User (uuid) {
let coins = 0; // Visible only inside this function
return {
uuid: uuid,
nickname: nickname,
getCoins: function () { return coins }
}
}
Inheritance is prototypal in Javascript: you take an object and you create a new object that inherits all its properties.
const parentObject = {/*key-value-pairs*/};
const childObject = Object.create(parentObject);
JavaScript has a new operator that makes it easier to handle inheritance and makes a function look like a class.
Recently also a class statement has been added to JavaScript but it is just sintactic shugar for the prototype pattern.
With that in mind, I suggest you read this article for a thorough introduction to JavaScript objects.