开发者

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 wi开发者_如何学运维thin the object?


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜