Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Konrad Pilch
2,435 PointsJS and Game
I have a question, iv just came across JS objects and this lets me to think.. and i was thinking:
When creating a game, we would make everything as objects? I mean a Hero would be object called hero, that has many functions inside him that he can do, and has his name assigned etc.. right?
So when creating enemies, there will be an object for each different enemy, and then the functions of thier health, armor, etc..
I am somewhat right?
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsThat sounds reasonable to me. I've used both constructor functions and factory functions. Objects are great at encapsulating related things together - into what other languages might call a class. Whichever you choose shouldn't matter much - perhaps there are performance differences? may be worth testing at https://jsperf.com/. Other than that, main difference is in the use - or absence of - the this keyword.
// constructor function
var Dog = function() {
// private properties
var sound = "woof!";
// public methods
this.speak = function() { console.log(sound); }
}
// factory function
var Cat = function() {
// private properties
var sound = "meow!";
// the returned object can be thought of as the object's API
return {
speak: function() { console.log(sound); }
}
}
var peanut = new Dog();
peanut.speak(); // "woof!";
peanut.sound; // undefined
var grumpy = Cat();
grumpy.speak(); // "meow!"
grumpy.sound; // undefined
Maximillian Fox
Courses Plus Student 9,236 PointsYou are somewhat correct in that a good approach is to create everything as objects.
However with the enemies, you could have one main enemy class, and then different types of subclasses which extend the main enemy class, which detail enemies with different properties and methods. Then you could create new instances of those classes within your script.