Understanding Javascript generated by Typescript compiler

后端 未结 2 1239
孤城傲影
孤城傲影 2021-01-23 00:53

if i type this simple typescript code:

class Point2D
{
    constructor(public x: number, public y: number)
    {
    }
} 

and look at the gener

2条回答
  •  有刺的猬
    2021-01-23 01:25

    The reason it is computed as such is due to the functional nature of JavaScript an the class nature of the code being converted. The typescript is attempting to convert the code as accurately as possible and since Javascript is classless. It writes the code to simulate a class, Of course the class emulation is not the most efficient way of achieving the desired result, but has been demonstrated to be more readable to the programmer with a class based background. Also while there are multiple ways to achieve the desired results in JavaScript, the way it was transcribed most accurately represents the source it was provided since it is indeed based on a class. As for the difference the generated code uses a constructor to create an object that is then used to create objects based on it. This is how you end up with the ability to use it like a class since the objects you create with it will inherit from it just like a class in the language from witch you are converting. The function you have provided will only assign the values to itself when invoked where as the generated code will create objects that include the functionality inherently. To clarify more: your function would be used like this Point2D(5,4) It is also worth pointing out here that in JavaScript using a capital to name an object is reserved by convention only for Objects constructed like the one the code generated that are expected to use the 'new' method when used. The generated code would be used like this pointA = new Point2D(5,4). Because the code returns the function Point2D and it is invoked using () at that time, pointA becomes an instance of Point2D which again is acting like a class, Also, if you were to add any properties, functions etc. to Point2D, pointA would automatically pick those up as well, whether it had already been instantiated or not. Hopefully this clears it up for you, there are other differences, but it is not clear exactly how much information you are looking to acquire.

提交回复
热议问题