理解 类:由 3 个点延伸组成一个三角形?
Understanding Classes: Compose a Triangle from extending 3 points?
问题:
我怎样才能拿一个三角形 Class 扩展 Point(supers(?)) 并组成一个看起来像这样的对象:
// "name":"Thomas The Triangle",
// "points": [
// {age: "2015-05-28T06:23:26.160Z", x: 1, y: 1 },
// {age: "2015-05-28T06:23:26.161Z", x: 0, y: 3 },
// {age: "2015-05-28T06:23:26.164Z", x: 2, y: 3 }
// ]
JS:
class Point {
constructor(x, y){
this.name = "Point"
this.age = new Date();
this.x = x;
this.y = y;
}
}
class Triangle extends Point{
constructor(coords, name) {
super(coords[0][0], coords[0][1]); //this line is best I could do but not correct
this.name = name
}
}
let t1 = new Triangle([[1,1],[0,3],[2,3]], 'Thomas The Triangle')
console.log(t1);
**
Live code for ES6
**
看起来 Triangle
不需要延长 Point
。而是将多个 Point 对象组合成点数组。像这样:
class Triangle {
constructor(coords, name) {
this.points = coords.map((point) => {
return new Point(...point);
});
this.name = name;
}
}
问题: 我怎样才能拿一个三角形 Class 扩展 Point(supers(?)) 并组成一个看起来像这样的对象:
// "name":"Thomas The Triangle",
// "points": [
// {age: "2015-05-28T06:23:26.160Z", x: 1, y: 1 },
// {age: "2015-05-28T06:23:26.161Z", x: 0, y: 3 },
// {age: "2015-05-28T06:23:26.164Z", x: 2, y: 3 }
// ]
JS:
class Point {
constructor(x, y){
this.name = "Point"
this.age = new Date();
this.x = x;
this.y = y;
}
}
class Triangle extends Point{
constructor(coords, name) {
super(coords[0][0], coords[0][1]); //this line is best I could do but not correct
this.name = name
}
}
let t1 = new Triangle([[1,1],[0,3],[2,3]], 'Thomas The Triangle')
console.log(t1);
**
Live code for ES6
**
看起来 Triangle
不需要延长 Point
。而是将多个 Point 对象组合成点数组。像这样:
class Triangle {
constructor(coords, name) {
this.points = coords.map((point) => {
return new Point(...point);
});
this.name = name;
}
}