3

I have an object parameter and it has a property value. it is thusly defined

var parameter = {
    value : function() {
        //do stuff
    }
};

my problem is that, in some cases, value needs to have a property of its own named length

can i do that? it seems that putting this.length = foo does not work, neither does parameter.value.length = foo after the object declaration.

2
  • Do you mean that the returned object from value() needs to have a length? Commented Jan 25, 2011 at 17:22
  • no, i check value's length and iterate over it as though it were an array. Commented Jan 25, 2011 at 17:37

3 Answers 3

6

The problem seems to be with the selection of the word 'length'. In JavaScript, functions are objects and can have properties. All functions already have a length property which returns the number of parameters the function is declared with. This code works:

var parameter = {
    value : function() {
        //do stuff
    }
};

parameter.value.otherLength = 3;

alert(parameter.value.otherLength);
Sign up to request clarification or add additional context in comments.

4 Comments

Ken is correct I believe (I was beaten to this answer)...see ejohn.org/blog/javascript-method-overloading and ejohn.org/apps/learn/#87
ok, well, that makes things interesting. the reason i picked length is because value is an array in most cases and i wanted the function to seem like an array in that sense. but thank you.
Thank you VERY much for that first link ken. I had a different issue that this addresses completely.
:D You might also try looking at how jQuery instantiates itself -- a jQuery object (the result of a jQuery query, such as jQuery('*')), uses a length property to emulate arrays. You have lots of options here, though!
2

parameter.value.length should work. Run the following:

var obj = {
    method: function () {}
};
obj.method.foo = 'hello world';
alert(obj.method.foo); // alerts "hellow world"

Functions are technically objects, so they can have methods and properties of their own.

1 Comment

but not if i try to define length
-1

Try this. It should work:

var parameter = {
  value : {
    length : ''
  }
}

var newLength = parameter.value.length = 10;
alert( newLength ); // output: 10

If I understand your question, basically, in object literals notation, an object can contain another object and so on. So to access the inner object and its properties, you just have to do the dot natation as usual following the hierarchy. In the above case 'parameter' then the inner-object, 'value', then the inner-object property, 'length'.

1 Comment

My issue comes from defining value as a function.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.