0

So the following won't work:

var Foo = {
    array1 : ['apples', 'oranges', 'grapes'],
    arrayLength : array1.length // error
}

Is there any way I can access Foo.array1's length within the object?

3 Answers 3

2

You'll need to do it like this:

var Foo = {};
Foo['array1'] = ['apples', 'oranges', 'grapes'];
Foo['arrayLength'] = Foo['array1'].length;

Or like this (much cleaner IMHO):

var Foo = function() {
   var a = ['apples', 'oranges', 'grapes'];
   return {'array1': a, 'arrayLength':a.length};
}();

Another alternative:

function Foo(array) {
   this.array1 = array;
   this.arrayLength = array.length;
   //other stuff...
}

var f = new Foo(['apples', 'oranges', 'grapes']);

But really, this doesn't make much sense to me, you're already storing the array, why do you need to cache the length property?`

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

1 Comment

Your last question made me think why I still needed to cache a property. Thanks Jacob! I need to learn more about closures ...
0

or:

 var x;
 var Foo = {
     array1 : x = ['apples', 'oranges', 'grapes'],
     arrayLength : x.length
 };
 alert(Foo.arrayLength);

clearly not so nice, the Jacob Relkin' solution is better

1 Comment

If you're going to use a variable, might as well actually assign it in the same line that you define it.
0

You can't really access a property like that.
You can use a function such as :

var Foo = {
    array1 : ['apples', 'oranges', 'grapes'],
    arrayLength : function(){ return this.array1.length;}
}

which is actually a good thing and I recommend using this since the Foo.array1 array can change in time, and you probably want the arrayLength field to be updated.

Another option would be to use a closure that returns your object literal :

var Foo = (function(){
    var array1 = ['apples', 'oranges', 'grapes'];
    return {
        array1 : array1,
        arrayLength : array1.length
    };
})();

If you really want to get into oop stuff, you can use "constructors" and prototypes for this :

var FooClass = function(array){this.init(array);}
FooClass.prototype = new function(){
    this.init = function(array){
        this.array1 = array;
        this.updateArrayLength();
    };
    this.updateArrayLength = function(){
         this.arrayLength =  this.array1.length;
    };
    this.array1 = [];
    this.arrayLength = 0;        
};

var Foo = new FooClass(['apples', 'oranges', 'grapes']),
    Foo2 = new FooClass(['bananas', 'limes', 'grapefruits']);

1 Comment

I happened to have already suggested your second example in my answer.

Your Answer

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