最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

properties - Function with a property in javascript? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jan 25, 2011 at 17:33 Ken Browning 29.1k6 gold badges58 silver badges68 bronze badges asked Jan 25, 2011 at 17:21 griotspeakgriotspeak 13.3k13 gold badges46 silver badges54 bronze badges 2
  • Do you mean that the returned object from value() needs to have a length? – Hemlock Commented Jan 25, 2011 at 17:22
  • no, i check value's length and iterate over it as though it were an array. – griotspeak Commented Jan 25, 2011 at 17:37
Add a ment  | 

3 Answers 3

Reset to default 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);

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.

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'.

发布评论

评论列表(0)

  1. 暂无评论