【发布时间】:2018-07-22 01:10:14
【问题描述】:
对于一个新项目,我正在尝试 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 类的函数输出到调试控制台时,它给了我一个错误,提示中间值不是函数。经过一些快速研究后,大多数答案都指出必须缺少分号。我希望能解决我的问题。
提前致谢,
帕斯卡
【问题讨论】:
-
为什么要从构造函数返回?
-
不要将分号放在方法声明的末尾。
标签: javascript function class ecmascript-6