And I want it applied all the instances of the class Sprite
(past and future), not to one single instance.
You're quite right that if you were dealing with a primitive (like your "testing"
string), you could just add it to Sprite.prototype
and it would appear on all Sprite
objects without any crosstalk between them.
Also if position was an array it would have been easy: just write Sprite.prototype.position=[0,0]
While it's true that the array would show up on all Sprite
objects, they would have the potential for cross-talk, because they'd all share the same array:
var sprite1 = new Sprite();
var sprite2 = new Sprite();
Sprite.prototype.position = [0,0];
sprite1.position[0] = 42;
console.log(sprite2.position[0]); // "42"
If you don't mind them all sharing the same array/object, you can do exactly the same thing with your class:
Sprite.prototype.position = new Position(/*...*/);
Again, they will all share one Position
object.
If you want each sprite instance to have its own Position
object (or array), independent of the one on other instances, you have only two choices:
Modify the Sprite
constructor to assign the object/array to the instances as they're created.
Spin through all Sprite
objects ever created and add the object/array.
Obviously you can't do #2 unless you have references to those objects.
It may well be that you don't have to do anything to Sprite.prototype
at all, depending on how you want to handle a sprite not having a position
. For example:
function doSomethingWithASprite(sprite) {
if (!sprite.position) {
// Doesn't have a position yet, give it one
sprite.position = new Position(/*...relevant args...*/);
}
}
Similarly, any time you want to get a sprite's position:
var x = sprite.position && sprite.position.x;
That will give you undefined
if the sprite doesn't have a position yet.
A final option for you: Make position
a function:
Sprite.prototype.position = function(x, y) {
// Make sure we have a position
if (!this.position) {
this.position = new Position(/*...relevant args...*/);
}
if (typeof x === "undefined") {
// Getter, return the current position
return this.position;
}
else {
// Setter, set the current position
this.position.x = x;
this.position.y = y;
}
};