Classes in TypeScript
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
A class is a blueprint for objects. Follow a twelve-line program as new builds two objects, the constructor fills their fields, and a method changes one object's balance through this, until 75 is printed. Then see TypeScript's part: typed fields, a private balance that tsc refuses to let outside code touch, and why that check is erased from the JavaScript that runs.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01What does writing class Account { ... } create on its own?
A class only describes the fields and methods. new Account(...) is what builds an object from it and runs the constructor.
02What does constructor(public owner: string) {} do?
It is a parameter property: the modifier public turns the parameter into a field of the same name, filled from the argument, even with an empty body.
03After ada.deposit(50) and console.log(ada.deposit(25)), and then bob = new Account("Bob"), what is bob's balance?
Each object has its own fields. deposit changed this.balance, and this was ada, so ada has 75 and bob starts at 0.
04Why does tsc reject ada.balance = 1000; written outside the class?
tsc reports error TS2341: Property 'balance' is private and only accessible within class 'Account'.
05What happens to private in the JavaScript tsc writes?
Classes are JavaScript, so the class stays, but TypeScript's private is only checked by tsc. JavaScript's #fields are the run-time kind of private.
المسرد
- Class
- A blueprint that describes the fields and methods every object made from it will have.
- Object (instance)
- One thing built from a class with new. Each has its own copy of the fields.
- Field
- A named value stored inside each object, such as balance. In TypeScript it has a type.
- Constructor
- The special method new runs to set up a fresh object.
- Method
- A function defined in a class, called on an object, like ada.deposit(50).
- this
- Inside a method, the object the method was called on: the one before the dot.
- Parameter property
- A constructor parameter with a modifier such as public or private; it declares and fills a field of the same name.
- private
- A TypeScript modifier: only code inside the class may use the member. tsc checks it; the running JavaScript does not.
الملاحظات والمصادر
- TypeScript's private is a "soft" private: it is only enforced during type checking, so plain JavaScript (or bracket access like ada["balance"]) can still reach the field at run time. JavaScript's own #private fields are enforced at run time.
- The JavaScript shown is what tsc 5.9 writes with --target es2022. Older targets turn the class into a function with the method on Account.prototype; the program still prints 75.
- By default tsc still writes the .js file even when it reports an error such as TS2341; the noEmitOnError setting stops that.
- The code on the card is real and runnable: it prints 75.
اختبار يتاح بعد الخطوة الأخيرة.