javascript - ES6 类中明确定义但未定义的函数

标签 javascript function class ecmascript-6

对于一个新项目,我正在尝试 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)

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 值不是函数。经过一些快速研究后,大多数答案都指出必须缺少分号。我希望我的问题能得到解决。

提前致谢,

帕斯卡

最佳答案

您的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);

关于javascript - ES6 类中明确定义但未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461255/

相关文章:

javascript - 对返回不可链接的 Promise<void> 的函数的异步支持

python - 在 python 中,根据函数变量更改 MySQL 查询

python - 作为计时器运行的功能下降了吗?

.net - 私有(private)嵌套类

javascript - anchor 转换与选项卡的 Bootstrap 单击功能冲突

Javascript:日期比较

javascript - 统计或资源 : which gets disabled first (more often than others)? 图片或 Javascript?

Excel函数返回月份之间的差异?

java - Wicket - 运行时类重新加载

C++ 预处理器在类关键字之后和类名之前定义