简体   繁体   English

编写 class 并实现功能

[英]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.我需要编写 class Circle 并实现以下功能。

1.Properties:center coordinates and radius. 1.属性:中心坐标和半径。

2.Define constructor with parameters for initialize object. 2.定义带有参数的构造函数,用于初始化object。

3.Define method, which returns length f circumference(L= 2 * π * R). 3.Define方法,返回长度f圆周(L= 2 * π * R)。

4.Define method,which return copy of current object. 4.定义方法,返回当前object的副本。

5.Define method which converts current state of object to string and return result. 5.定义将object的当前state转换为字符串并返回结果的方法。

6.Define static method of circumference for given radius. 6.定义static给定半径的圆周方法。

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).如果您希望使用现代 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.如果您想将面积和周长作为方法而不仅仅是 getter 方法。 Then you should drop the get prefix before the method name.然后,您应该在方法名称之前删除 get 前缀。 As that means these methods are getters因为这意味着这些方法是吸气剂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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