【问题标题】:Struggling with ES6 features of Javascript挣扎于 JavaScript 的 ES6 特性
【发布时间】:2019-02-23 01:05:01
【问题描述】:

我只是在探索 ES6。我可以看到更新中的值,但我正在努力使用类方法。

class Item{
  constructor(name){
    this.name=name;
  }
}
class Park extends Item{
  constructor(name, numberoftrees, size){
    super(name);
    this.numberoftrees=numberoftrees;
    this.size=size;
  }
  classifyPark(){
    const classification = new Map();
    classification.set(1, "SMALL");
    classification.set(2, "MEDIUM");
    classification.set(3, "LARGE");
    console.log(`${this.name} park is sized: ${classification.get(this.size)} and has
    ${this.numberoftrees} trees.`)
  }
}



var Park1 = new Park();
Park1.name=prompt('ENTER NAME OF PARK');
Park1.numberoftrees=prompt('ENTER # OF TREES');
Park1.size=parseInt(prompt('ENTER SIZE'));


function reportPark(parks){
  console.log("PARK REPORT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  parks.forEach(item=>item.classifyPark());
}
reportPark(parks);

为什么我需要classifyPark 作为我的类的方法?为什么我不应该只创建一个单独的地图并直接访问它?我正在学习一门 udemy 课程,但没有人在问答中回答这个问题,我完全糊涂了。

classifyPark 只是创建我们的地图,然后使用 size 属性作为地图中的键来控制台记录该值。是这样吗?这似乎是一种疯狂的做事方式。

【问题讨论】:

  • 是的,classification Map 似乎完全没用,因为 classifyPark 函数从不使用它。这是整个代码吗?
  • 如果你有这样的怀疑,那就是代码异味。相信你的直觉并质疑它的必要性。
  • 我现在意识到了它的价值。对象(在 javascript 中是一种对象类型)可以具有属性或方法,因此分类公园方法允许我们从本质上附加它将创建的地图。我确信还有另一种方法可以将地图附加为属性,但这是一个非常聪明的解决方案。

标签: javascript class dictionary methods ecmascript-6


【解决方案1】:

这是一个简单的例子,但它说明classifyPark 使用this 访问来自Item 类的变量。

console.log(`${this.name} park is sized: ${classification.get(this.size)} and has ${this.numberoftrees} trees.`)

在“现实世界”中,类方法通常更复杂,可以使用类变量和其他类方法来做更复杂的事情。

另一个微不足道的例子,但也许更有帮助

class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  area() {
    return 3.14*this.radius*this.radius;
  }

  circumference() {
    return 3.14*this.radius;
  }

}

const circle = new Circle();
console.log(circle.area());
console.log(circle.radius());

areacircumference 放在Circle 上而不是使用辅助函数的想法是封装逻辑。圆知道如何计算自己的半径和周长。

【讨论】:

  • 这是有道理的!谢谢!很好的例子!
猜你喜欢
  • 2017-06-04
  • 2012-08-30
  • 2023-04-06
  • 2014-08-30
  • 1970-01-01
  • 2013-06-03
  • 2015-08-24
  • 2021-08-05
  • 2012-01-06
相关资源
最近更新 更多