我的三角形区域构造函数有什么问题
What is wrong with my Triangle area constructor?
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());
我试图使用苍鹭公式找到三角形的面积,但我收到错误:"意外标记这个"。有谁知道那可能是什么?
var result =
{
return (this.sideOne + this.sideTwo + this.sideThree)/2;
};
应该是
var result = (this.sideOne + this.sideTwo + this.sideThree) / 2;
问题是您已经在对象表示法中定义了result
变量。
只需直接将值分配给结果即可。当在三角形对象上调用heronFormula
时,result
已经在形成heronFormula
函数闭包的作用域中。
小提琴
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());
试试这个:
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());
var result =
{
return (this.sideOne + this.sideTwo + this.sideThree)/2;
};
应该是
var result = function() { ... };
相关文章:
- 我不知道我的编码有什么问题.(JavaScript)
- 我的流星路线出了什么问题
- 此nodeValue替换代码有什么问题
- 这个正则表达式的日期/时间有什么问题
- 我的CSS/Javascript下拉菜单测试代码出了什么问题
- 这个代码出了什么问题?(Jquery)
- 下面的Reg表达式出了什么问题
- 鼠标事件,我的代码出了什么问题
- 这个javascript语法有什么问题
- 动态创建foreignGroup并将其添加到svg中有什么问题
- 此代码中动态生成选择框有什么问题
- 我的javascript有什么问题?.className
- 这个 ajax.js 代码有什么问题
- JS代码有什么问题,让我知道代码是否可以改进
- 我的 Browserify JavaScript 代码有什么问题
- 图像上传功能将++(+1)副本添加到下一次上传.出了什么问题或如何重置“选定图像”
- 使用 Javascript 动态删除行.我的代码有什么问题
- AngularJS:这个注入我的控制器有什么问题
- 这个jQuery if语句有什么问题
- JavaScript:有人能告诉我我的代码出了什么问题吗?