Javascript构造函数与Typescript类

时间:2017-05-03 12:14:50

标签: javascript

我最近开始学习Javascript并尝试围绕几个重要的概念。根据我的理解,到目前为止,Javascript没有类,它使用构造函数而不是类来为对象创建蓝图。例如:

// javascript code
var Car = function() {
  // this is a private variable
  var speed = 10;

  // these are public methods
  this.accelerate = function(change) {
    speed += change;
  };

  this.decelerate = function() {
    speed -= 5;
  };

  this.getSpeed = function() {
    return speed;
  };
};    
    
// typescript code
class Car {

  public speed: number = 10;

  public acceleration(accelerationNumber: number): void {
    this.speed += accelerationNumber;
  }

  public decelerate(decelerateNumber: number): void {
    this.speed += decelerateNumber;
  }

  public getSpeed(): number {
    return this.speed;
  }
}

上面的Typescript代码更有意义,因为我们有一个为该类对象创建蓝图的类。但是,在Javascript中,这个蓝图是用函数创建的。那么这意味着Javascript中的构造函数是否与类在Typescript / Java / etc中的作用相同。

1 个答案:

答案 0 :(得分:1)

与那个Typescript类的正确对应是:

var Car = function () {
  this.speed = 10;
};

Car.prototype.accelerate = function (change) {
  this.speed += change;
};

Car.prototype.decelerate = function () {
  this.speed -= 5;
};

Car.prototype.getSpeed = function () {
  return this.speed;
};

Car函数,即构造函数,基本上是constructor()中的class;它是初始化新实例的执行方式。 prototype上的所有函数都是在所有实例共享的类中定义的其他方法。