Consider such a code (javascript):
var jsonTmp = '{ "groups": [ { "name": "G1", "status": "inactive" }, { "name": "G2", "status": "active"}, { "name": "G3", "status": "inactive" }] }'
var dataTmp = JSON.parse(jsonTmp)
function g(key) {
this.key = key;
this.name;
this.status;
this.setStatus = function (status) {
this.status = status;
}
this.setName = function (name) {
this.name = name;
}
}
function main() {
this.groups = []
this.createGroups = function () {
$.each(dataTmp.groups, function (key, group) {
myGame.groups[key] = new g(key)
myGame.groups[key].setStatus(group.status)
myGame.groups[key].setName(group.name)
})
}
this.getGroupsWithStatus = function (status) {
var groups = [];
$.each(myGroups, function (key, group) {
if ( group.status == status ) { groups.push( key )}
})
return groups
}
}
var myGame = new main();
var myGroups = myGame.groups
myGame.createGroups();
myGame.getGroupsWithStatus("inactive")
I am attempting to make good and effective, also readable OOP logic, and since it is my first fully oop project please make some advices:
I create game (myGame), that takes dynamically (from jsonTmp) data to create multiple objects, called groups. Because amount of groups may be different they do not have a name like
var group1 = new g("abc") var group2 = new g("cde")
They are stored without a instialized name in array of objects (here myGame.groups or myGroups).
Question 1: is that a good idea of storing objects to access them via key of object in array? I will be also searching for particular value of property of objects - like status here with getGroupsWithStatus. Do you have any better ideas to solve such a logic?
Question 2: can i set a name of instance in different way then
var instanceName = new g("abc")
and do i really need it if my objects are stored in array?
Question 3: In createGroups method I would rather use some kind of pointer instead of myGame.groups[key]:
this.createGroups = function () {
$.each(dataTmp.groups, function (key, group) {
var currentGroup;
currentGroup = new g(key)
currentGroup.setStatus(group.status)
currentGroup.setName(group.name)
myGame.groups[key] = currentGroup;
})
}
I guess that solution is more readable. Am i right?
Sorry for maybe dumb questions, but i always used structural languages and oop logic is quite hard for me to use, and most of tutorials say about how to make class or inherit props of objects. Maybe you can also provide some good oop in practice tutorials? Thansk in advance. Kalreg.