我正在探索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作为我班级的方法?为什么我不应该创建一个单独的Map并直接访问它?我正在遵循一个udemy课程,但在问答环节中没有人回答这个问题,我只是完全糊涂了。
classifyPark只是创建我们的地图,然后使用size属性作为地图中的一个键来控制记录该值。是吗?这似乎是一种疯狂的做事方式。
这是一个简单的例子,但它说明了classifyPark
通过使用Item
来访问this
类中的变量。
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());
将area
和circumference
放在Circle
上而不是使用辅助函数的想法就是封装逻辑。圆知道如何计算自己的半径和周长。