开发者

Function with a property in javascript?

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

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

my proble开发者_JAVA技巧m 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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜