user982078
user982078

Reputation:

Javascript: accessing own Object's variables

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?

Upvotes: 0

Views: 82

Answers (3)

gion_13
gion_13

Reputation: 41533

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']);

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163228

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?`

Upvotes: 2

user652649
user652649

Reputation:

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

Upvotes: 0

Related Questions