如何使用构造函数's的输出,以便将值插入到对象中

how to use a constructor function's output to insert values to an object?

本文关键字:插入 对象 输出 构造函数 何使用      更新时间:2023-09-26

我为一个圆创建了一个构造函数,其中有一个半径值,还有两个函数来计算面积和周长,我试图将面积和周长的计算值作为要构建的对象的元素传递,但它不起作用。

    function Circle (r) {
        this.radius = r;
        this.area = function () {
            var a =  Math.PI * this.radius * this.radius;
            // tried this 
            this.areaaaa = a;
        };

        this.perimeter = function(){
            var p =  Math.PI * this.radius * 2;
            // tried this too
            this.perimeterrrr = p;
            };

    };
    var x = new Circle(5);
    console.log(x);
    // output is {radius:5, area: [function], perimeter: [function]}
// desired output is {radius:5, area: [function],areaaa:78.54, perimeter: [function], perimeterrrr:31.42}

您可以使用ECMA 6 getter和setter

function Circle (r) {
    this.radius = r;
    Object.defineProperty(this, "area", { get: function () { return Math.PI * this.radius * this.radius; } })
};
var circle = new Circle(5)
circle.radius //5
circle.area  //78.53981633974483

问题是这些函数定义中的代码永远不会运行。试试这个。

function Circle (r) {
    this.radius = r;
    this.a = Math.PI * this.radius * this.radius;
    this.p = Math.PI * this.radius * 2;
};
var x = new Circle(5);
console.log(x);