Javascript TypeError:Undefined不是函数

时间:2014-07-01 12:02:39

标签: javascript

我在Codecademy上学习Javascript,我正在尝试创建一个告诉我矩形周长的函数。出现的错误是:

SyntaxError: Unexpected end of input

我的代码是:

function Rectangle(height, width) {
  this.height = height;
  this.width = width;
};
  this.calcArea = function() {
      return this.height * this.width;
  };
  // put our perimeter function here!
  this.calcPerimeter = function() {
      return this.height * 2 + this.width * 2;
  };
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();

非常感谢任何帮助/建议,谢谢:)

3 个答案:

答案 0 :(得分:1)

this.calcareathis.calcperimeter超出了Rectangle的范围。您需要它们在Rectangle对象的括号内作为成员函数。像这样:

function Rectangle(height, width) {
  this.height = height;
  this.width = width;

  this.calcArea = function() {
      return this.height * this.width;
  }
  // put our perimeter function here!
  this.calcPerimeter = function() {
      return this.height * 2 + this.width * 2;
  }
}

答案 1 :(得分:0)

您在错误的位置关闭了Rectangle类。

您的代码问题是calcPerimetercalcAreaRectangle级之外。因此,当你在undefined中执行rex.calcArea();函数时。

使用

function Rectangle(height, width) {
    this.height = height;
    this.width = width;
    //}; removed from here
    this.calcArea = function () {
        return this.height * this.width;
    };
    this.calcPerimeter = function () {
        return this.height * 2 + this.width * 2;
    };
}; //Place closing brace here

var rex = new Rectangle(7, 3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();

答案 2 :(得分:0)

您需要使用

Rectangle.prototype,如下:

function Rectangle(height, width) {
  this.height = height;
  this.width = width;
}
Rectangle.prototype.calcArea = function() {
      return this.height * this.width;
};
Rectangle.prototype.calcPerimeter = function() {
      return this.height * 2 + this.width * 2;
  };
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();

为类Method创建Rectangle

在您的代码中您的方法area()perimeter指的是this对象,在这种情况下指向window。所以没用。使this指向Rectangles对象。您需要使用Rectangle.prototype.methodName=function(){//Here this =Rectangle Obj };

className.prototype.methodName

在javascript中创建public方法(methodName),该类可以由该类的objects访问。

DEMO

希望它有帮助! :!)