Function with property in javascript?

I have an object parameterand it has a property value. he is defined in this way

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

My problem is that in some cases the value must have a property of its own name length

Can I do it? it seems that put is this.length = foonot working, and after declaring the object is not parameter.value.length = foo.

+3
source share
3 answers

The problem is choosing the word "length". In JavaScript, functions are objects and may have properties. All functions already have a length property, which returns the number of parameters declared by the function. This code works:

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

parameter.value.otherLength = 3;

alert(parameter.value.otherLength);
+6
source

parameter.value.lengthmust work. Follow these steps:

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

, .

+2

. :

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

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

If I understand your question, mainly in the notation of object literals, the object may contain another object, etc. Thus, in order to access the internal object and its properties, you just need to execute a sequence of points, as usual, after the hierarchy. In the above case, “parameter” is the internal object, “value”, then the property of the internal object is “length”.

-1
source

Source: https://habr.com/ru/post/1787756/


All Articles