如何使用构造函数的输出来向对象插​​入值?

时间:2016-05-12 17:41:39

标签: javascript oop

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

    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}

2 个答案:

答案 0 :(得分:4)

您可以使用ECMA 6 getters and setters

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

答案 1 :(得分:2)

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

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);