After three entrances writing about TypeScript, a new entrance for a new and interesting topic: classes. Previous one was related to functions.
Classes are a concept that it doesn’t exist in Javascript
If you program or develop in other programming languages such as Python or C#, you use to deal with classes to solve the problem when creating large apps, but in Javascript, this concept is not clear.
In theory, Javascript has 3 different forms of declarating a class (I’m not repeating code, but you can see the three was in detail here): http://www.phpied.com/3-ways-to-define-a-javascript-class/. Also, yu should be aware of the benefits of using patterns in Javascript (and jQuery): http://shichuan.github.io/javascript-patterns/. I like this page because they recommend the better way, although you can use the one you like, of course!
When I write that classes doesn’t exist in Javascript is because there is no keyword, such as class, as you have in other languages. In mi opinion, the way of creating properties, methods and functions is not clear at all, becuase you can do exatly the same using several forms, but also, you have to use Prototype.
Prototype-based programming is an OOP model that doesn’t use classes, but rather accomplishes behavior reuse (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects.
Copying the C# model
The new version of Javascript EMACScript6 introduce classes: www.sitepoint.com/understanding-ecmascript-6-class-inheritance/. Another features introduced with classes are getters y setters (you can use them since EMACScript5, but not in EMACScript 3), and this way, accessing information to-from a class is better and easier.
class FooBar{ constructor(foo) { this.foo = foo; this._bar = 0; } get bar() { return this._bar;} set bar(value) { this._bar = value; } doFoo() {console.log("Hi! "+ this.foo);} }
In my opinon, this way of defining classes is closer to Python or C# than Javascript, so, learning TypeScript for me is the best way of understanding Javascript. I have said it several times that I hate Javascript, because everything is not recommended but everything is allowed.
Private Variables
TypeScript make Javascript simpler
Obviously, if you‘ve read the entries to which I linked, it is because you know the problem better or have applied some of their solutions. Do not you think that in any case, everything is very complex? I, I think so, hence to learn Javascript is complicated.
So, let’s create some classes in TypeScript.