0

I wanna make the following piece of JS code, but, instead of 3 different variables, I want to group them in an object for easy future reference in the script.

const container = document.querySelector('.container');
const container_height = parseInt(window.getComputedStyle(container).getPropertyValue('height'));
const container_width = parseInt(window.getComputedStyle(container).getPropertyValue('width'));

In my understanding of objects as a group of variables I produced the following:

const container = {
    elm    : document.querySelector('.container'),
    height : parseInt(window.getComputedStyle(this.elm).getPropertyValue('height')),
    width  : parseInt(window.getComputedStyle(this.elm).getPropertyValue('width'))
}

Isn't 'this' how you should go about referring to other variables within the object?

Edit: Terminal Error: Uncaught ReferenceError: elm is not defined.

BelgianCoder
  • 101
  • 3

1 Answers1

1

container.elm will work. this refers to that particular property value.

Consider the part after : as a block with its own scope

I think the link that is shared for the duplicate is a good one you can have a look at it.

But here in your particular case I believe that you should not include elm as you have done here. The element itself is a separate entity so a better approach would be like below

const _elm = document.querySelector('.container');
const container = {
    elm    : _elm,
    height : parseInt(window.getComputedStyle(_elm).getPropertyValue('height')),
    width  : parseInt(window.getComputedStyle(_elm).getPropertyValue('width'))
}
muasif80
  • 5,586
  • 4
  • 32
  • 45
  • I changed 'this' into 'container' and now it gives me a new Error: Uncaught ReferenceError: Cannot access 'container' before initialization. Does this mean I have to initialise an object before I can get the computed style out of it? – BelgianCoder Sep 22 '19 at 15:09