Node.js 类

Javascript的类都声明为函数:

  1. function Shape () {
  2. this.X = 0;
  3. this.Y = 0;
  4. this.move = function (x, y) {
  5. this.X = x;
  6. this.Y = y;
  7. }
  8. this.distance_from_origin = function () {
  9. return Math.sqrt(this.X*this.X + this.Y*this.Y);
  10. }
  11. }
  12. var s = new Shape();
  13. s.move(10, 10);
  14. console.log(s.distance_from_origin());

你可以随时向你的类中添加任意数量的属性和方法:

  1. var s = new Shape(15, 35);
  2. s.FillColour = "red";

声明类的函数是它的构造函数!

原型和继承

默认情况下,JavaScript中的所有对象都有一个原型对象。原型对象是它们继承属性和方法的机制。以下代码显示如何使用原型创建继承。更改Shape类,以便所有继承对象也获得X和Y属性,以及你声明的方法:

  1. function Shape () {
  2. }
  3. Shape.prototype.X = 0;
  4. Shape.prototype.Y = 0;
  5. Shape.prototype.move = function (x, y) {
  6. this.X = x;
  7. this.Y = y;
  8. }
  9. Shape.prototype.distance_from_origin = function () {
  10. return Math.sqrt(this.X*this.X + this.Y*this.Y);
  11. }
  12. Shape.prototype.area = function () {
  13. throw new Error("I don"t have a form yet");
  14. }
  15. var s = new Shape();
  16. s.move(10, 10);
  17. console.log(s.distance_from_origin());
  18. function Square() {
  19. }
  20. Square.prototype = new Shape();
  21. Square.prototype.__proto__ = Shape.prototype;
  22. Square.prototype.Width = 0;
  23. Square.prototype.area = function () {
  24. return this.Width * this.Width;
  25. }
  26. var sq = new Square();
  27. sq.move(-5, -5);
  28. sq.Width = 5;
  29. console.log(sq.area());
  30. console.log(sq.distance_from_origin());

上面的代码生成以下结果。

原型继承

你可以进一步扩展一个新的类叫Rectangle,继承自Square类:

  1. function Rectangle () {
  2. }
  3. Rectangle.prototype = new Square();
  4. Rectangle.prototype.__proto__ = Square.prototype;
  5. Rectangle.prototype.Height = 0;
  6. Rectangle.prototype.area = function () {
  7. return this.Width * this.Height;
  8. }
  9. var re = new Rectangle();
  10. re.move(25, 25);
  11. re.Width = 10;
  12. re.Height = 5;
  13. console.log(re.area());
  14. console.log(re.distance_from_origin());

我们可以使用运算符instanceof来检查继承。

  1. console.log(sq instanceof Square); // true
  2. console.log(sq instanceof Shape); // true
  3. console.log(sq instanceof Rectangle); // false
  4. console.log(re instanceof Rectangle); // true
  5. console.log(sq instanceof Square); // true
  6. console.log(sq instanceof Shape); // true
  7. console.log(sq instanceof Date); // false