简体   繁体   English

Javascript构造函数与Typescript类

[英]Javascript constructor functions vs Typescript classes

I've recently started learning Javascript and trying to wrap my head around few important concepts. 最近,我开始学习Javascript,并尝试将一些重要的概念缠住我的头。 As per my understanding till now, Javascript does not have classes, it uses constructor functions instead of classes to create blueprint for the objects. 根据我到目前为止的理解,Javascript还没有类,它使用构造函数而不是类来为对象创建蓝图。 Example: 例:

// 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;
  }
}

The above Typescript code makes much more sense because we have a class that creates a blueprint for that class objects. 上面的Typescript代码更有意义,因为我们有一个为该类对象创建蓝图的类。 But, in Javascript this blueprint is being created with a function. 但是,在Javascript中,此蓝图是通过函数创建的。 So does that mean constructor function in Javascript does the same thing that classes does in Typescript/Java/etc.? 那么这是否意味着Javascript中的构造函数与类在Typescript / Java / etc中所做的事情一样?

The correct equivalent to that Typescript class would be: 该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;
};

The Car function, the constructor function, is basically what constructor() is in a class ; Car函数(构造函数)基本上是class constructor() it is what is executed to initialise a new instance. 这是初始化新实例所执行的操作。 All functions on prototype are the other methods defined inside the class shared by all instances. prototype上的所有函数是在所有实例共享的类内定义的其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM