对于一个新项目,我正在尝试ES6类。但是,出现以下错误:
main.js:4 Uncaught TypeError: $container.setBackgroundColor is not a function
对于我来说,这很奇怪,因为$ container所指的类显然包含函数setBackgroundColor。我在类中的其他函数也遇到了该错误。
主要的JavaScript代码
window.onload = function () {
var $container = new View("container");
$container.setBackgroundColor("#E9425B");
document.body.append($container);
};
查看课程
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);
};
}
我已经做了一些搜索,并且在将View类的函数输出到调试控制台时,它给我一个错误,表明Intermediate值不是一个函数。经过快速研究后,大多数答案都指出必须缺少分号。希望我的问题有解决办法。
预先感谢
帕斯卡
答案 0 :(得分:2)
您的return this.view;
返回的是创建的元素,而不是类实例化,因此它无权访问类方法。删除return语句,以便返回实例化本身,然后从.append($container);
更改为.append($container.view);
。
此外,通过将对元素的引用保存在.view
属性中,只需再次引用.view
属性就可以再次获得它-您当前的get() { return document.getElementsByTagName(this.id);
将不起作用,因为id
不是标签名称。
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);
答案 1 :(得分:1)
删除返回this.view;来自构造函数