-1

I want to define an object, and use a function to populate an array as one of the members of the object. I have tried using a function both inside and outside the object definition, but neither seems to work. Is this possible? Here is a simplified version of what I am trying to do:

<!DOCTYPE html>
<html>
<body>
<p>object function test.</p>
<p id="demo"></p>

<script>
var test_object = {
    num1: 1,
    num2: 10,
    nums: make_array(this.num1, this.num2)       
};

function make_array(firstnum, lastnum) {
       myArray = [];
       for (i=firstnum; i <= lastnum; i++){
         myArray.push(i);
       }
    return myArray;
};
document.getElementById("demo").innerHTML = test_object.nums;
</script>
</body>
</html>

It seems that num1 and num2 are undefined when they are passed to the function. What am I doing wrong?

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
cmhodge
  • 1
  • 3

3 Answers3

0

You have to use a getter here for the desired result,

var test_object = {
    num1: 1,
    num2: 10,
    get nums() {
      return make_array(this.num1, this.num2)       
    }
};

And let me tell why your code is not working as expected, the this inside of that object literal would point to the upper context, not the object itself.

This would be a better read for you.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

In this context, the this refers to the parent object (the window, if the code is running in a browser), not the test_object you're in the middle of defining:

var test_object = {
    num1: 1,
    num2: 10,
    nums: make_array(this.num1, this.num2)       
};

If you want the end result to be a plain object, the easiest solution is probably to separate the assignments so you can refer to the object by name:

var test_object = {
    num1: 1,
    num2: 10
}
test_object.nums = make_array(test_object.num1, test_object.num2);

(The ES6 getter referred to in another answer is also a possibility, though it works slightly differently (and doesn't work in some old browsers): the above would evaluate the array immediately; getters are evaluated when the value is requested. So with a getter, if for example you changed test_object.num1 before reading test_object.nums you'd get a different answer. This may or may not be what you want.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
-1

The problem is that myArray insider your function make_array is not declared.