Andrei Oniga
Andrei Oniga

Reputation: 8559

javascript object literal - object creation

I'm trying to create an object in which some properties rely on other previously defined properties, while trying to rely on object literals. Otherwise put, I'm trying to accomplish something like the following code (which is incorrect):

var mesh = {
            offset   : $('#mesh').offset(),
            position : $('#mesh').position(),
            height   : win.height - this.offset.top - 12,   
            width    : win.width - this.offset.left - 12,   
            limits   : {}
        }

as opposed to something of this sort (which works):

var mesh = {};
        mesh.offset   = $('#mesh').offset();
        mesh.position = $('#mesh').position();
        mesh.height   = win.height - mesh.offset.top - 12;  
        mesh.width    = win.width - mesh.offset.left - 12;
        mesh.limits = {};

So my question is rather simple: what is actually wrong with the first block of code and how can I correct it in order to create those new properties based on previously defined ones?

Upvotes: 1

Views: 257

Answers (2)

Thomas Jones
Thomas Jones

Reputation: 4962

you can create a constructor function

var Mesh = function(mesh_id){
    var mesh = $(mesh_id);
    this.offset = mesh.offset();
    this.position = mesh.position();
    this.height = win.height - this.offset.top - 12;
    this.width = win.width - offset.left - 12
    this.limits = {}


};

and then use it like this

var myMesh = new Mesh('#mesh')

*note that this code is assuming some variable win is defined. you have probably defined it as var win = $(window)

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375494

There is no name that references the currently-building object literal. You'll need to use the second form, or have the values in variables that you can reference:

var offset = $('#mesh').offset();
var mesh = {
    offset   : offset,
    position : $('#mesh').position(),
    height   : win.height - offset.top - 12,   
    width    : win.width - offset.left - 12,   
    limits   : {}
}

Upvotes: 3

Related Questions