0

For this object in javascript:

div = 
     {
     id: (changeable value),
     html = 'div id="divName'+id+'"></div>

}

This is the most basic form that I can present the problem. I have a function that creates the above object and pushes that into an array. Except the above reports :

'Uncaught ReferenceError: id is not defined'

It's not a variable but an object property, so I'm not confused as to what the error is, but I'm a little unclear on how to reference, as a variable, a property within the same object.

I have tried added a method to the object - but that method is also undefined

div = 
     {
     id: (changeable value),
     html = 'div id="divName'+getId()+'"></div>',
     getId()
        {
        return this.id;
    },
}
Ricardo Gonzalez
  • 1,827
  • 1
  • 14
  • 25
altruios
  • 986
  • 1
  • 10
  • 29
  • In addition to the dupe `id` and `div.id` are *different things*. Using `id` in the object literal doesn't refer to the `id` property of the same object - it will always try to reference a variable called `id`. Since there isn't any, it throws an error. – VLAZ Oct 15 '19 at 21:07
  • ...yes. That is my question. I know they are different things. My question reiterated with variation: How do you make the 'id' inside the html property the same as div.id (which does not work)? – altruios Oct 15 '19 at 22:08
  • 1
    As shown in the dupe. Although I'd wonder if you're going about this the right way. – Dave Newton Oct 15 '19 at 22:12

1 Answers1

1

If you want to try a method try something like that

var div = {
  id: (changeable value),
  html: function(){
    return 'div id = "divName' + this.id + '"></div>'
  }
}
Amir Makram
  • 12,030
  • 3
  • 13
  • 25