我的Triangle区域构造函数有什么问题?

时间:2016-03-09 20:47:18

标签: javascript

function triangle(sideOne, sideTwo, sideThree)
{
    this.sideOne = sideOne;
    this.sideTwo = sideTwo;
    this.sideThree = sideThree;

    var result = 
    {
        return (this.sideOne + this.sideTwo + this.sideThree)/2;
    };

    this.heronFormula = function()
        {
            return Math.sqrt(result*(result-this.sideOne)*(result-this.sideTwo)*
            (result-this.sideThree));         
        };

}

var newTriangle = new triangle(5,6,7);

console.log(newTriangle.heronFormula());

我正在尝试使用苍鹭的公式找到三角形的区域,但我收到错误:"意外的标记这个"。有谁知道那可能是什么?

4 个答案:

答案 0 :(得分:2)

var result = 
    {
        return (this.sideOne + this.sideTwo + this.sideThree)/2;
    };

应该是

var result = (this.sideOne + this.sideTwo + this.sideThree) / 2;

问题是您已在对象表示法中定义了result变量。

直接将值分配给结果。在三角形对象上调用heronFormula时,result已经在范围内,形成heronFormula函数的闭包。

<强> Fiddle

答案 1 :(得分:1)

function Triangle(sideOne, sideTwo, sideThree)
{
    this.sideOne = sideOne;
    this.sideTwo = sideTwo;
    this.sideThree = sideThree;

    this.result = (this.sideOne + this.sideTwo + this.sideThree)/2;
}

Triangle.prototype.heronFormula = function() {
   return Math.sqrt(this.result*(this.result-this.sideOne)*(this.result-this.sideTwo)*(this.result-this.sideThree));         
};


var newTriangle = new Triangle(5,6,7);

console.log(newTriangle.heronFormula());

答案 2 :(得分:1)

试试这个:

https://jsfiddle.net/dznatab1/

function triangle(sideOne, sideTwo, sideThree)
{
   this.sideOne  = sideOne;
   this.sideTwo  = sideTwo;
   this.sideThree = sideThree;
   var result = (this.sideOne + this.sideTwo + this.sideThree)/2;  

   triangle.prototype.heronFormula  = function(){
     return Math.sqrt(result*(result-sideOne)*(result-sideTwo)*(result-sideThree)); 
   }; 
}
var newTriangle = new triangle(5,6,7);
console.log(newTriangle.heronFormula());

答案 3 :(得分:0)

var result = 
{
    return (this.sideOne + this.sideTwo + this.sideThree)/2;
};

应该是

var result = function() { ... };