Reputation: 3
For a new project I'm trying out the ES6 classes. However, I get the following error:
main.js:4 Uncaught TypeError: $container.setBackgroundColor is not a function
That seems weird to me as the class that $container is referring to, clearly contains the function setBackgroundColor. I also get that error with other functions in the class.
Main javascript code
window.onload = function () {
var $container = new View("container");
$container.setBackgroundColor("#E9425B");
document.body.append($container);
};
View Class
class View{
constructor(id){
this.id = id;
this.view = document.createElement(this.id);
return this.view;
};
get(){
return document.getElementsByTagName(this.id);
};
setText(text){
this.get().innerText = text;
};
setBackgroundColor(color){
this.get().style.backgroundColor = color;
};
create(id){
if(id != null){
this.id = id;
}
};
addChild(child){
console.log(child);
this.get().append(child);
};
}
I've done some searching, and when outputing a function of the View class to the debugging console it gives me an error that suggests the Intermediate value is not a function. After some quick research most answers state there must be a missing semicolon. I hope there's a fix for my problem.
Thanks in advance,
Pascal
Upvotes: 0
Views: 731
Reputation: 370679
Your return this.view;
is returning the created element, not the class instantiation, so it has no access to the class methods. Remove the return statement so the instantiation itself is returned, and change to .append($container);
to .append($container.view);
.
Also, by saving the reference to the element in the .view
property, you can get it again simply by referencing the .view
property again - your current get() { return document.getElementsByTagName(this.id);
won't work because the id
isn't a tag name.
class View {
constructor(id) {
this.id = id;
this.view = document.createElement(this.id);
}
get() {
return this.view;
}
setText(text) {
this.get().innerText = text;
}
setBackgroundColor(color) {
this.get().style.backgroundColor = color;
}
create(id) {
if (id != null) {
this.id = id;
}
}
addChild(child) {
console.log(child);
this.get().append(child);
}
}
var $container = new View("container");
$container.setBackgroundColor("#E9425B");
$container.setText('container text');
document.body.append($container.view);
Upvotes: 2