Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components, but this may feel a bit awkward to programmers more comfortable with an object-oriented approach, where classes inherit functionality and objects are built from these classes. Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers can build their applications using this object-oriented class-based approach. In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript. Show
ClassesLet’s take a look at a simple class-based example:
The syntax should look familiar if you’ve used C# or Java before. We declare a new class 1. This class has three members: a property called 2, a constructor, and a method 3. You’ll notice that in the class when we refer to one of the members of the class we prepend 4. This denotes that it’s a member access. In the last line we construct an instance of the 1 class using 6. This calls into the constructor we defined earlier, creating a new object with the 1 shape, and running the constructor to initialize it. InheritanceIn TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance. Let’s take a look at an example:
This example shows the most basic inheritance feature: classes inherit properties and methods from base classes. Here, 8 is a derived class that derives from the 9 base class using the 0 keyword. Derived classes are often called subclasses, and base classes are often called superclasses. Because 8 extends the functionality from 9, we were able to create an instance of 8 that could both 4 and 5. Let’s now look at a more complex example.
This example covers a few other features we didn’t previously mention. Again, we see the 0 keywords used to create two new subclasses of 9: 8 and 9. One difference from the prior example is that each derived class that contains a constructor function must call 0 which will execute the constructor of the base class. What’s more, before we ever access a property on 1 in a constructor body, we have to call 0. This is an important rule that TypeScript will enforce. The example also shows how to override methods in the base class with methods that are specialized for the subclass. Here both 9 and 8 create a 5 method that overrides the 5 from 9, giving it functionality specific to each class. Note that even though 8 is declared as an 9, since its value is a 8, calling 1 will call the overriding method in 8:
Public, private, and protected modifiersPublic by defaultIn our examples, we’ve been able to freely access the members that we declared throughout our programs. If you’re familiar with classes in other languages, you may have noticed in the above examples we haven’t had to use the word 3 to accomplish this; for instance, C# requires that each member be explicitly labeled 3 to be visible. In TypeScript, each member is 3 by default. You may still mark a member 3 explicitly. We could have written the 9 class from the previous section in the following way:
ECMAScript Private FieldsWith TypeScript 3.8, TypeScript supports the new JavaScript syntax for private fields:
This syntax is built into the JavaScript runtime and can have better guarantees about the isolation of each private field. Right now, the best documentation for these private fields is in the TypeScript 3.8 . Understanding TypeScript’s tsclass Animal { #name: string; constructor(theName: string) { this.#name = theName; }} new Animal("Cat").#name;Property '#name' is not accessible outside class 'Animal' because it has a private identifier.18013Property '#name' is not accessible outside class 'Animal' because it has a private identifier.Try8TypeScript also has its own way to declare a member as being marked 8, it cannot be accessed from outside of its containing class. For example:
TypeScript is a structural type system. When we compare two different types, regardless of where they came from, if the types of all members are compatible, then we say the types themselves are compatible. However, when comparing types that have 8 and 1 members, we treat these types differently. For two types to be considered compatible, if one of them has a 8 member, then the other must have a 8 member that originated in the same declaration. The same applies to 1 members. Let’s look at an example to better see how this plays out in practice:
In this example, we have an 9 and a 6, with 6 being a subclass of 9. We also have a new class 9 that looks identical to 9 in terms of shape. We create some instances of these classes and then try to assign them to each other to see what will happen. Because 9 and 6 share the 8 side of their shape from the same declaration of 4 in 9, they are compatible. However, this is not the case for 9. When we try to assign from an 9 to 9 we get an error that these types are not compatible. Even though 9 also has a 8 member called 1, it’s not the one we declared in 9. Understanding tsclass Animal { private name: string; constructor(theName: string) { this.name = theName; }} new Animal("Cat").name;Property 'name' is private and only accessible within class 'Animal'.2341Property 'name' is private and only accessible within class 'Animal'.Try1The 1 modifier acts much like the 8 modifier with the exception that members declared 1 can also be accessed within deriving classes. For example,
Notice that while we can’t use 1 from outside of 8, we can still use it from within an instance method of 9 because 9 derives from 8. A constructor may also be marked 1. This means that the class cannot be instantiated outside of its containing class, but can be extended. For example,
Readonly modifierYou can make properties readonly by using the 3 keyword. Readonly properties must be initialized at their declaration or in the constructor. 0 Parameter propertiesIn our last example, we had to declare a readonly member 1 and a constructor parameter 5 in the 6 class. This is needed in order to have the value of 5 accessible after the 6 constructor is executed. Parameter properties let you create and initialize a member in one place. Here’s a further revision of the previous 6 class using a parameter property: 1 Notice how we dropped 5 altogether and just use the shortened 01 parameter on the constructor to create and initialize the 1 member. We’ve consolidated the declarations and assignment into one location. Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or 3, or both. Using 8 for a parameter property declares and initializes a private member; likewise, the same is done for 3, 1, and 3. AccessorsTypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object. Let’s convert a simple class to use 08 and 09. First, let’s start with an example without getters and setters. 2 While allowing people to randomly set 10 directly is pretty handy, we may also want enforce some constraints when 10 is set. In this version, we add a setter that checks the length of the 12 to make sure it’s compatible with the max-length of our backing database field. If it isn’t we throw an error notifying client code that something went wrong. To preserve existing functionality, we also add a simple getter that retrieves 10 unmodified. 3 To prove to ourselves that our accessor is now checking the length of values, we can attempt to assign a name longer than 10 characters and verify that we get an error. A couple of things to note about accessors: First, accessors require you to set the compiler to output ECMAScript 5 or higher. Downleveling to ECMAScript 3 is not supported. Second, accessors with a 08 and no 09 are automatically inferred to be 3. This is helpful when generating a 17 file from your code, because users of your property can see that they can’t change it. Static PropertiesUp to this point, we’ve only talked about the instance members of the class, those that show up on the object when it’s instantiated. We can also create static members of a class, those that are visible on the class itself rather than on the instances. In this example, we use 18 on the origin, as it’s a general value for all grids. Each instance accesses this value through prepending the name of the class. Similarly to prepending 4 in front of instance accesses, here we prepend 20 in front of static accesses. 4 Abstract ClassesAbstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. The 21 keyword is used to define abstract classes as well as abstract methods within an abstract class. 5 Methods within an abstract class that are marked as abstract do not contain an implementation and must be implemented in derived classes. Abstract methods share a similar syntax to interface methods. Both define the signature of a method without including a method body. However, abstract methods must include the 21 keyword and may optionally include access modifiers. 6 Advanced TechniquesConstructor functionsWhen you declare a class in TypeScript, you are actually creating multiple declarations at the same time. The first is the type of the instance of the class. 7 Here, when we say 23, we’re using 1 as the type of instances of the class 1. This is almost second nature to programmers from other object-oriented languages. We’re also creating another value that we call the constructor function. This is the function that is called when we 6 up instances of the class. To see what this looks like in practice, let’s take a look at the JavaScript created by the above example: 8 Here, 27 is going to be assigned the constructor function. When we call 6 and run this function, we get an instance of the class. The constructor function also contains all of the static members of the class. Another way to think of each class is that there is an instance side and a static side. Let’s modify the example a bit to show this difference: 9 In this example, 29 works similarly to before. We instantiate the 1 class, and use this object. This we have seen before. Next, we then use the class directly. Here we create a new variable called 31. This variable will hold the class itself, or said another way its constructor function. Here we use 32, that is “give me the type of the 1 class itself” rather than the instance type. Or, more precisely, “give me the type of the symbol called 1,” which is the type of the constructor function. This type will contain all of the static members of Greeter along with the constructor that creates instances of the 1 class. We show this by using 6 on 31, creating new instances of 1 and invoking them as before. It is also good to mention that changing static property is frowned upon, here 39 has 40 instead of 41 on 42. Using a class as an interfaceAs we said in the previous section, a class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces. Apa itu extend pada java?extends digunakan untuk mewariskan method dan property dari kelas induknya, sedangkan implements digunakan untuk mewariskan interface.
Apa itu constructor di javascript?Konstruktor atau contructor pada Javascript adalah method spesial yang berfungsi untuk inisialisasi ketika pembuatan obyek. Konstruktor dipanggil segera setelah obyek baru dibuat. Ciri dari konstruktor adalah nama method sama persis dengan nama kelasnya.
|