Hello! Please help me with this question: we have a parent class that is responsible for selecting the html document by classes:

function gtClassName(аргумент не передавал намерено, что бы разобраться с наследованием){ this.ElemClass = null; this.gtElemClas = document.getElementsByClassName(this.ElemClass); } 

There is also a heir class that accepts all properties of the parent class:

 function gtClassButtons(Buttons){ gtClassName.call(this); this.ElemClass = Buttons; return this.gtElemClas.ElemClass; } 

After I create a class object:

 var b = new gtClassButtons('B'); console.log(b); 

I get the result:

 gtClassButtons {ElemClass: "B", gtElemClas: HTMLCollection[0]} 

An empty HTML collection, but ElemClass no longer null .
People, tell me how to fix it and, if possible, explain why this approach was a failure.

  • document.getElementsByClassName (null) is how? - Jean-Claude
  • @ Jean-Claude, really simple, but the result may be rather unexpected :) - Grundy
  • @Grundy Well, the question was just rather as rhetorical. - Jean-Claude

1 answer 1

First, there is no inheritance in the code given in the question.

If you use the instanceof operator, you will see that b not an instance of gtClassName .

Secondly, the line with this.gtElemClas is executed immediately , it means that the used this.ElemClass is null , since this value was assigned to it by the string earlier

 this.ElemClass = null; 

And finally: a meaningless string

 return this.gtElemClas.ElemClass; 

gtElemClass is a collection of elements, the collection does not have an ElemClass field, so this string is equivalent to: return undefined;

Moreover, it is important to understand that if a complex object is returned from the constructor, then it will return, and no class object will be created, that is, calls with the new operator and without it will be equivalent.

  • I also thought that for porridge in the retour)) - Jean-Claude
  • Damn, with return et I gave a mistake I just copied the code and forgot to remove it, I used to check it before .. - shimba
  • And why there is no inheritance, perhaps gtClassName.call (this); doesn't pass properties to the gtClassButtons class? - shimba
  • @shimba, because inheritance is also a prototype - Grundy