3

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";
1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

0

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
   }
}();

1 Comment

Could you please adapt the concrete example to show for which parts of it the IEFE would be useful? a+b is a bit too abstract

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.