T
T
Timofei19972022-02-09 22:25:08
JavaScript
Timofei1997, 2022-02-09 22:25:08

How is enum implemented in JS from Typescript?

There is code in ts:

enum Membership {
    Simple,
    Standart,
    Premium
}


After compiling to js it looks like this:
var Membership;
(function (Membership) {
    Membership[Membership["Simple"] = 0] = "Simple";
    Membership[Membership["Standart"] = 1] = "Standart";
    Membership[Membership["Premium"] = 2] = "Premium";
})(Membership || (Membership = {}))
Можете, пожалуйста, объяснить, что выполняет эта часть кода: (Membership || (Membership = {})


And why is it all wrapped in a function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dark Hole, 2016-02-07
@dosya97

The essence of the question is not very clear.
As far as I understand, you are trying to insert new code into an existing tag. Or did I misunderstand something?
If this is a template, then you need to apply it again, if this is a new script, then you need a new tag
Yes, it seems to me that the error in ajaxGet is not your function?
Note that jQuery is just a JavaScript library. JavaScript doesn't process any script tag - jQuery doesn't.

A
Aetae, 2022-02-09
@Aetae

Because enum in typescript can merge:
Valid code:

enum Membership {
  Simple,
  Standart,
  Premium
}

enum Membership {
  SimpleX = 99
}

Why does the compiler not put it together if such things work at the compilation stage - I don’t know, but there are probably reasons.

D
Dmitry Belyaev, 2022-02-10
@bingo347

Can you please explain what this part of the code does: (Membership || (Membership = {})
If the value in Membership is not falsy (for example, an object), then pass a reference to it to the function, otherwise (if Membership is undefined) assign a new object to Membership and pass a reference to it to the function
And why is it all wrapped in a function?
It’s hard to say, I think someone copied the code from here to the code here and didn’t bother, since in both cases there is a declaration merging, which Aetae
already wrote about . In general, it’s worth learning about const enum , which leaves no artifacts in JS there are enough cases.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question