我需要将此代码转换为ES6,我是JS的新手,我不知道如何

问题描述 投票:1回答:1

我是JS的新手,并不熟悉旧版本,我有这个测试,我需要转换成Es6。有谁能帮助我理解我怎么做到这一点?

'use strict';
function Shape(id, x, y) {
 this.id = id;
 this.setLocation(x, y);
}
Shape.prototype.setLocation = function(x, y) {
 this.x = x;
 this.y = y;
};
Shape.prototype.getLocation = function() {
 return {
 x: this.x,
 y: this.y
 };
};
Shape.prototype.toString = function() {
 return 'Shape(' + this.id + ')';
};
function Circle(id, x, y, radius) {
 Shape.call(this, id, x, y);
 this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.toString = function() {
 return 'Circle > ' + Shape.prototype.toString.call(this);
};
javascript es6-modules
1个回答
0
投票

转换为classes

class Shape {
  constructor(id, x, y) {
    this.id = id;
    this.setLocation(x, y);
  }
  setLocation(x, y) {
    this.x = x;
    this.y = y;
  }
  getLocation = () => ({
    x: this.x,
    y: this.y
  })

  toString() {
    return `Shape(${this.id})`;
  }
}

class Circle extends Shape {
  constructor(id, x, y, radius) {
    super(id, x, y)
    this.radius = radius;
  }
  toString() {
    return `Circle> ${super.toString()}`;
  }
}

let shape = new Shape('shape', 5, 5);
let circle = new Circle('circle', 6, 6, 6);


console.log("Shape()",
  shape.getLocation(),
  shape.toString()
);
console.log("Circle()",
  circle.getLocation(),
  circle.toString()
);

希望这可以帮助,

© www.soinside.com 2019 - 2024. All rights reserved.