Search code examples
javascriptarraysobjectvariable-length-array

Can't get length of array/object in an Object of Javascript


box = {
  curBox: 0,
  boxes: document.getElementsByClassName('box'),
  size: this.boxes.length, //this one won't work
  orSize: Object.keys(this.boxes).length, //as well as this one
  preBox: function() {
    curBox -= 1
  },
  nexBox: function() {
    curBox += 1
  }
}

console.log(box.boxes.length); //This one works well!!!
<div class='active box BG_blue'>
  <meta name='title' content='Overview' /> ...
</div>

<div class='inactive box BG_orange'>
  <meta name='title' content='Career' /> ...
</div>

<div class='inactive box BG_red'>
  <meta name='title' content='Skills' /> ...
</div>

<div class='inactive box BG_awesome'>
  <meta name='title' content='Hobbies' /> ...
</div>

I tried to get the length of an array returned from getElementsByClassName. If I put it outside the object range, it work. But inside the object range, it won't. Right now, I would like to know a reason how come. I've test on other site (such as Mozilla) code editor but it only return the same result.


Solution

  • main reson is you are still initializing you Box object hence you can't access this. In other words your object is not fully formed at the time you are using this.

    what you can do is create a function and return it.

    boxes: function() {
      return function() { return this.boxes.length; },
    }
    

    I created a jsfiddle with improvements. https://jsfiddle.net/jz1thu26/.

    also note that you need to run your method when DOM is ready.