3
\$\begingroup\$

I'm a systems programmer teaching myself javascript. Prototypal inheritance is completely new to me, so I could use some best practices advice here.

I made a simple game (breakout) for my first practice project. Here is a simple example of a game object.

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
    this.__defineGetter__('width', function() {
        return sprite.width;
    });
    this.__defineGetter__('height', function() {
        return sprite.height;
    });
    this.__defineGetter__('rect', function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    });
}

Every object has an associate sprite and said sprite defines the width and height of the object. So, coming from C++, I defined a few of getters that depend on the sprite.

Any and all advice is obviously appreciated. Hopefully this example isn't overly trivial.

\$\endgroup\$
2
\$\begingroup\$

There hasn't been any standard for how to define getters and setters in Javascript until recently, so the implementations have various custom syntaxes, and not much seems to work in Internet Explorer... The defineGetter method is marked as non-standard and deprecated.

The thing that works reliably right now is to not use setters and getters at all, but methods that are named to indicate what they do (just as how it's done in Java).

(Of course, if you only need it to work in a specific browser, you can use whatever syntax works there. There are some syntax examples in the test code that I linked to above.)

To use prototypal interface, you put the methods in the prototype rather than in the object instance:

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
}

GameObject.prototype = {

    get_width: function() {
        return sprite.width;
    },
    get_height: function() {
        return sprite.height;
    },
    get_rect: function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    }

};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.