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());
我正在尝试使用苍鹭的公式找到三角形的区域,但我收到错误:"意外的标记这个"。有谁知道那可能是什么?
答案 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() { ... };