B
B
Banan442020-04-16 10:52:46
JavaScript
Banan44, 2020-04-16 10:52:46

Undefined, what is the reason?

I am writing a template:

class Element {
  constructor(html, props, url = document.body){
    this.html = html;
    this.props = props;
    this.url = url;
  }
  view(method = "insert"){
    let html = getHtml(this);

    if(method == "insert"){
      this.url.innerHTML = html;
    }
  }
}

function getHtml(element){
  let html = element.html;
  
  while(html.match("{{(.*?)}}")){

    let pattern = new RegExp("{{(.*?)}}");
    let key = Array.from(html.match(pattern))[1];
    let value = element.props[key]; 

    if(value instanceof Element){
      value = getHtml(key);
    }

    pattern = new RegExp(`{{${key}}}`);
    html = html.replace(pattern, value);

  }

  return html;
}



const firstElement = new Element(`
  First Element
  `);


const secondElement = new Element(`
  {{firstElement}}
  `, {
    firstElement: firstElement
  });

secondElement.view();

// TypeError: html is undefined
// Ссылается на эту строку: let propsLength = Array.from(html.matchAll(pattern)).length;

Why is it so? I did a check on Element, which means that the object must definitely have this html property

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogachev, 2020-04-16
@Banan44

I did a check on Element, which means that the object must definitely have this html property

if (value instanceof Element) {
    value = getHtml(key);
}

Well, value might be "instanceof Element", but then you call the getHTML function, passing in a string as a parameter. And, of course, it does not have any html property.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question