0

I'm making a simple library which turns JS objects into JS class componeents to register and use in HTML. I'm testing it with a simple object:

const myEle = {
state: {
message: `Hello World`
},
template: `<p> ${this.state.message} </p>`,
style: {
color: "red"
},
hooks: {
onClick: () => alert("Hi!")
},
attrs: {},
element: toComp(this.template, this.style, this.state, this.hooks, this.attrs)
}

Specifically, the error is with template. which gives me the error mentioned in the title, despite this.state.messagemaking snese ti ne. Why is that happening?

  • `this` is a little bit more complicated than that -- this answer goes into a bit more detail about why your code doesn't work: https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers – daniloxxv Apr 26 '22 at 05:49
  • check the answer: https://stackoverflow.com/a/4616262/2656795 you need a getter. – Chaitanya Chauhan Apr 26 '22 at 05:53

1 Answers1

0

You can't access the object during its initialization with object literal syntax.

This is invalid javascript:

const obj = {
  property1: 'hello',
  property2: property1
};

You can access it after its initialization:

const obj = {
  property1: 'hello',
};
obj.property2: property1;

Amir
  • 996
  • 7
  • 17