【问题标题】:Undefined function while clearly defined in ES6 class在 ES6 类中明确定义的未定义函数
【发布时间】: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


【解决方案1】:

您的return this.view; 正在返回创建的元素,而不是类实例化,因此它无法访问类方法。删除 return 语句,以便返回实例化本身,并将 .append($container); 更改为 .append($container.view);

另外,通过保存对 .view 属性中元素的引用,您可以通过再次引用 .view 属性再次获取它 - 您当前的 get() { return document.getElementsByTagName(this.id); 将不起作用,因为 id 不是t 标签名称。

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

【讨论】:

    【解决方案2】:

    移除 return this.view;来自构造函数

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2018-02-04
      • 1970-01-01
      • 2017-06-10
      • 2018-07-14
      • 2017-12-07
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      相关资源
      最近更新 更多