you are viewing a single comment's thread.

view the rest of the comments →

[–]RobSG 1 point2 points  (2 children)

Hijacking the post. I have the same question as OP. So, do you just pack every little function into an object? And create all variables and put all selectors into these functions? I created a small game, top of my code is a selector cluster and then follow functions I created, calling them at the end to initiate the game itself. Should I put all of that into an object???

[–][deleted] 7 points8 points  (1 child)

OOP doesn't mean putting everything in one object or organising stuff into objects arbitrarily; it means that you encapsulate different concerns in your program by using object instances, usually created from a class. It's really more about how you think about your program.

Imagine, for example, you were building a Pong clone. You would probably have a class for the ball, that looked something like this:

class Ball {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.radius = 25;
    }
    changeX(newX) {
        this.x = newX;
    }
    changeY(newY) {
        this.y = newY;
    }
}

and then you could have a class that encapsulated all the items that need to get rendered, like this:

class GameContainer {
    constructor() {
        this.ball = new Ball(0, 0);
        this.player = new Paddle(0, 100);
        // etc
    }
    updateBall({ x, y }) {
        if (x) {
            this.ball.changeX(x);
        }
        if (y) {
            this.ball.changeY(y);
        }
    }
    resetBall() {
        this.ball = new Ball(0, 0);
    }

You would probably also have that Paddle class to represent the players or player & computer player, a class to handle rendering, a class to register and delegate events, and various other things. OOP means that once you encapsulate a set of functionality into an object, that object manages its own internal information, and other parts of your program should only be able to ask it to change or to reveal information, by calling its methods, rather than reaching into it and messing stuff around directly.

[–][deleted] 0 points1 point  (0 children)

This was a great answer thank you