views:

59

answers:

3

I have an object which has several properties that are set when the object is created.

This object recently changed to object literal notation, but I've hit a bit of a problem that searching on the net doesn't reveal.

Simply stated I need to do this:

Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
    var self = {
        id: _id,
        // other properties
        links: [],
        for (var i=0,j=0;i<8;i++) { //<- doesn't like this line
            var k = parseInt(_links[i]);
            if (k > 0) {
                this.links[j++] = k;
            }
        },
        // other methods
    };
    return self;
};

How do I initialise a property in the constructor in object literal notation?

A: 

You can't. Object notation doesn't allow this. However, you can add the properties AFTER initializing your object.

By the way, self is a defined object already, which is an alias for the window object. While you ARE defining a temporary object named self [and thus, you aren't getting rid of window.self] this isn't something you shold be doing. Act as if self was a keyword and your current usage of it is illegal.

ItzWarty
It worries me that two people tried this approach
James Westgate
Two people tried this approach?
graham.reeds
+3  A: 
  1. You can create the array on the fly using an anonymous function:

    Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
        var self = {
            id: _id,
            // other properties
            links: (function() {
                var a = [];
                for (var i=0;i<8;i++) {
                    var k = parseInt(_links[i]);
                    if (k > 0) {
                        a.push(k);
                    }
                }
                return a;
            })(),
            // other methods
        };
        return self;
    };
    
  2. You can do it after the literal is defined:

    Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
        var self = {
            id: _id,
            // other properties
            links: [],
            // other methods
        };
        for (var i=0,j=0;i<8;i++) {
            var k = parseInt(_links[i]);
            if (k > 0) {
                self.links[j++] = k;
            }
        }
        return self;
    };
    
Max Shawabkeh
+1  A: 

For this specific example, you could use an anonymous function, like this:

Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
    var self = {
        id: _id,
        // other properties
        links: (function(){
            var links = [];
            for (var i=0;i<8;i++) {
                var k = parseInt(_links[i]);
                if (k > 0) {
                    links.push(k);
                }
            }
            return links;
        })(),
        // other methods
    };
    return self;
};
Christopher Parker