【问题标题】:Function call returning undefined函数调用返回未定义
【发布时间】:2021-08-11 01:10:23
【问题描述】:

由于 TestDome d.o.o. 提出 DMCA 删除请求,此问题的内容已被删除

【问题讨论】:

  • 你必须使用()来调用方法。 screen.diagonal()。否则使用 getter 而不是方法。设置screen.dimensions也是如此。
  • 这能回答你的问题吗? JS getters and setters inside a class?
  • 这不是你在 JS 中定义构造函数的方式。
  • @Ivar 是对的。 Screen(_width... 应该是 constructor(_width...

标签: javascript ecmascript-2016


【解决方案1】:

您必须使用括号实际调用函数...

class Screen {  
  Screen(_width, _height){
    this.width=_width;
    this.height=_height;
  }
  diagonal() {
    return Math.sqrt(Math.pow(this.width, 2) + Math.pow(this.height, 2));
  }
  
  dimensions(definition) {
    var dimensions = definition.split('x')
    this.width = parseInt(dimensions[0]);
    this.height = parseInt(dimensions[1]);
  }
}

var screen = new Screen(0, 0);
screen.dimensions('500x300');
screen.width = 400;
console.log(screen.diagonal()); 

【讨论】:

  • 由于某种原因我得到了 NaN
  • @nidhi 你也注意到screen.dimensions('500x300')了吗?
  • Screen(_width, _height){ 应该是 constructor(_width, _height){ 否则 screen.height 将是 undefined
【解决方案2】:

删除函数参数周围的引号。即 ('500x300') 应该是 (500x300)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多