首先,我是学习编码的新手。 在我的代码中,我想创建一个函数“Square”,它通过使用你传入的length参数创建一个方形对象。另一个函数来计算它的周长。这是我的代码,我找不到我的错,你能不能帮助我?
function Square(length){
this.length = length;
}
var calcPerimeter = function() {
return this.sideLength * 4;
};
var calcArea = function() {
return this.sideLength * this.sideLength ;
};
var p = square.calcPerimeter();
var a = square.calcArea();
var calcPerimeter2 = function(n){
return n*4;
};
var square1 = new Square(5);
square1.calcPerimeter2();
答案 0 :(得分:1)
也许这就是你要找的东西:
function Square(length){
this.sideLength = length;
}
Square.prototype.calcPerimeter = function() {
return this.sideLength * 4;
};
Square.prototype.calcArea = function() {
return this.sideLength * this.sideLength ;
};
var square = new Square(5);
console.log(square.calcPerimeter());
console.log(square.calcArea());
答案 1 :(得分:1)
试试这个......
function Square(length){
this.length = length; //Constructor
}
Square.prototype.calcPerimeter = function(){
return this.length * 4;
}
Square.prototype.calcArea = function() {
return this.length * this.length;
}
var s = new Square(5);
s.calcPerimeter();
使用此模式,您可以在javascript中模拟继承,此模式称为" Prototype"。希望这对你有用.... 此致
答案 2 :(得分:0)
我不知道你在这段代码中做了什么,但我会像这样做代码:
function Square(length){
this.length = length;
this.calcSideLength = function() {
this.sideLength = /* Your code to calculate sideLength */;
};
this.calcPerimeter = function() {
return this.sideLength;
};
this.calcArea = function() {
return this.sideLength * this.sideLength;
};
this.calcPerimeter2 = function(n) {
return n*4;
};
}
var square = new Square(5);
var p = square.calcPerimeter();
var a = square.calcArea();
var square1 = new Square(5);
square1.calcPerimeter2(/* send a number */);