user3376708
user3376708

Reputation:

Clean Way to Build a JavaScript Object

I am just starting with Javascript and I am not certain if I have declared these correct for an object type declaration. Is there a better way and more readable way to declare a variable as a class in Javascript or is this the simplest way.

The blueObject is just and empty object from what I have read. Is this the only way to create a simple object type in Javascript or is there a better and more readable way?

Code:

    var blueObject={}; //Creates and object 
    var redObject={};  //Creates and object

    blueObject.x=0;
    blueObject.y=200;
    blueObject.dx=2;
    blueObject.width=48;
    blueObject.height=48;
    blueObject.image=new Image();
    blueObject.image.src="blueplus.png";

    context.drawImage(blueObject.image, 0, 0);
    blueObject.blueImageData=context.getImageData(0, 0, blueObject.width,
                                                  blueObject.height);
    context.clearRect(0,0,theCanvas.width, theCanvas.height);

    redObject.x=348;
    redObject.y=200;
    redObject.dx=-2;
    redObject.width=48;
    redObject.height=48;
    redObject.image=new Image();
    redObject.image.src="redcircle.png";

Upvotes: 3

Views: 169

Answers (3)

Jonn
Jonn

Reputation: 1674

This is probably the cleanest way for your purposes.

var blueObject = {
    x: 0,
    y: 200,
    dx: 2,
    width: 48,
    height: 48,
    image: new Image()
};

var redObject = {
    x: 348,
    y: 200,
    dx: -2,
    width: 48,
    height: 48,
    image: new Image();
};

blueObject.image.src = "blueplus.png";
redObject.image.src = "redCircle.png";

context.drawImage(blueObject.image, 0, 0);
blueObject.blueImageData = context.getImageData(0, 0, blueObject.width,
                                              blueObject.height);
context.clearRect(0, 0, theCanvas.width, theCanvas.height);

Also see this answer to learn about more formal ways of creating a JavaScript object.

Upvotes: 4

Anders Nygaard
Anders Nygaard

Reputation: 5552

I like the revealing module pattern that allows you to have a private scope. What you are doing is legal, but you are modifying the object from the outside which is often a bad practice.

var myClass = function(a, b){ // constructor
   var a = a;
   var b = b; 
   var c = a + b;

   return { // public signature
      c: c
   }
}();

Upvotes: 0

QuentinB
QuentinB

Reputation: 133

You can create a Class Color like this :

ColorClass = function(aX, aY, ..., aSrc){
    this.x = aX;
    this.y = aY;
    ...
    this.image = new Image();
    this.image.src = aSrc;
}

Then you can instanciate your two objects like this :

var blueObject = new ColorClass(0, 200, 2, ..., "blueplus.png"),
    redObject = new ColorClass(348, 200, ..., "redcircle.png");

Upvotes: 0

Related Questions