Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set length property of JavaScript object

Tags:

javascript

Let's say I have a JavaScript object:

function a(){
    var A = [];
    this.length = function(){
        return A.length;
    };
    this.add = function(x){
        A.push(x);
    };
    this.remove = function(){
        return A.pop();
    };
};

I can use it like so:

var x = new a();
x.add(3);
x.add(4);
alert(x.length()); // 2
alert(x.remove()); // 4
alert(x.length()); // 1

I was trying to make .length not a function, so I could access it like this: x.length, but I've had no luck in getting this to work.

I tried this, but it outputs 0, because that's the length of A at the time:

function a(){
    var A = [];
    this.length = A.length;
    //rest of the function...
};

I also tried this, and it also outputs 0:

function a(){
    var A = [];
    this.length = function(){
        return A.length;
    }();
    //rest of the function...
};

How do I get x.length to output the correct length of the array inside in the object?

like image 426
Rocket Hazmat Avatar asked Jun 20 '11 14:06

Rocket Hazmat


1 Answers

You could use the valueOf hack:

this.length = {
    'valueOf': function (){
        return A.length;
    },
    'toString': function (){
        return A.length;
    }
};

Now you can access the length as x.length. (Although, maybe it's just me, but to me, something about this method feels very roundabout, and it's easy enough to go with a sturdier solution and, for example, update the length property after every modification.)

like image 65
Casey Chu Avatar answered Sep 22 '22 06:09

Casey Chu