1

Here is some javascript code that I have:

   var screenWidth = 1280;
   var screenHeight = 720;

   var shapeComtainer = {
    name : "bender",
    offsetX : 100,
    offsetY : 100,
    width : screenWidth - 2*offsetX,
    height : screenHeight - 2*offsetY,
   };

I am getting the error offsetX and offsetY are not defined. This is in the lines where I am calculating width and height. The issue is that my width and height is dependent upon other variables inside the same object.

Is there a better/correct way to have a javascript object that represents information such as offsets and size information?

5

4 Answers 4

4

This won't be possible as already evident from the error message. Though, you could do the following:

var shapeContainer = {
    name : "bender",
    offsetX : 100,
    offsetY : 100,
    getwidth : function() { return screenWidth - 2 * this.offsetX },
    getheight : function() { return screenHeight - 2 * this.offsetY },
};

http://jsfiddle.net/XQGDB/

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

Comments

2

As an addition to Xander's answer: It is also possible, to use only one function that wraps around the whole object at once.

var shapeContainer = new function() {
    this.name = "bender";
    // ...
    this.width = screenWidth - 2 * this.offsetX;
};

Comments

1

Just because no one mentioned it so far, this is also a prime example for ECMAscript5's getter functions:

var defProps = Object.defineProperties;

var shapeComtainer = {
    name : "bender",
    offsetX : 100,
    offsetY : 100
};

defProps(shapeComtainer, {
    width: {
        get: function(){ return screenWidth - 2*this.offsetX; }
    },
    height: {
        get: function(){ return screenHeight - 2*this.offsetY; }
    }
});

And then you can just access it like:

shapeComtainer.height;

1 Comment

Very elegant! Maybe I was just looking for this kind of getter concept. Thanks.
-1

You must use shapeComtainer.offsetX and shapeComtainer.offsetY

6 Comments

this does not refer to the object though.
@Felix Kling you are right but now it's work I test it on firefox
And how exactly are you using this? If in this way: var a = {b: 42, c: a.b}; then it will not work. At the moment you want to access shapeComtainer (or a in this case), it does not exist yet. If you do it differently then you should post it.
I use set this in firefox console: var screenWidth = 1280; var screenHeight = 720; var shapeComtainer = { name : "bender", offsetX : 100, offsetY : 100, width : screenWidth - 2*shapeComtainer.offsetX, height : screenHeight - 2*shapeComtainer.offsetY, }; console.info(shapeComtainer.width); //print 1080
If you use that code, I get an error in Firefox as well, in the Web Console and Firebug... maybe shapeComtainer was already defined through your previous attempts.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.