简体   繁体   中英

write class and implement functionality

I have a problem or I didn't get it. I need to write class Circle and implement following functionality.

1.Properties:center coordinates and radius.

2.Define constructor with parameters for initialize object.

3.Define method, which returns length f circumference(L= 2 * π * R).

4.Define method,which return copy of current object.

5.Define method which converts current state of object to string and return result.

6.Define static method of circumference for given radius.

Here's my decision and I'm stuck.

 function circle(radius) { this.radius = radius; this.area = function () { return Math.PI * this.radius * this.radius; }; this.perimeter = function () { return 2*Math.PI*this.radius; }; } var c = new circle(3); console.log('Area =', c.area().toFixed(2)); console.log('perimeter =', c.perimeter().toFixed(2));

If you're looking to implement the same functionality with modern javascript (ECMAScript). Here is the below approach

 class circle{ constructor( radius ){ this.radius = radius; } get area(){ return Math.PI * this.radius * this.radius; } get perimeter(){ return 2*Math.PI*this.radius; } } var c = new circle(3); console.log('Area =', c.area.toFixed(2)); console.log('perimeter =', c.perimeter.toFixed(2));

If you want to make area and perimeter as method not just getter methods. Then you should drop the get prefix before the method name. As that means these methods are getters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM