Advertisement
runnig

javascript classes

May 24th, 2024
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // @ts-check
  2.  
  3. class Title {
  4.   #title;
  5.  
  6.   /**
  7.    * @param {string} title
  8.    */
  9.   constructor(title) {
  10.     if (typeof title != 'string') {
  11.       throw new Error('input argument must be a string');
  12.     }
  13.     if (title.length > 80) {
  14.       throw new Error('Title is too long');
  15.     }
  16.     this.#title = title;
  17.   }
  18.  
  19.   get title() {
  20.     return this.#title;
  21.   }
  22. }
  23.  
  24. class Content {
  25.   #content;
  26.   /** @param {string} content */
  27.   constructor(content) {
  28.     if (typeof content != 'string') {
  29.       throw new Error('input argument must be a string');
  30.     }
  31.     this.#content = content;
  32.   }
  33.  
  34.   get content() {
  35.     return this.#content;
  36.   }
  37. }
  38.  
  39. class Url {
  40.   #url;
  41.   /** @param {string} url */
  42.   constructor(url) {
  43.     if (typeof url != 'string') {
  44.       throw new Error('input argument must be a string');
  45.     }
  46.     if (!url.startsWith('http://') && !url.startsWith('https://')) {
  47.       throw new Error('Invalid URL');
  48.     }
  49.     this.#url = url;
  50.   }
  51.  
  52.   get url() {
  53.     return this.#url;
  54.   }
  55. }
  56.  
  57.  
  58. class Post {
  59.   /**
  60.    * @param {Title} title
  61.    * @param {Content} content
  62.    * @param {Url} imageUrl
  63.    */
  64.   constructor(title, content, imageUrl) {
  65.     if (!(title instanceof Title)) {
  66.       throw new Error('title must be an instance of Title');
  67.     }
  68.     if (!(content instanceof Content)) {
  69.       throw new Error('content must be an instance of Content');
  70.     }
  71.     if (!(imageUrl instanceof Url)) {
  72.       throw new Error('imageUrl must be an instance of Url');
  73.     }
  74.     this._title = title;
  75.     this._content = content;
  76.     this._imageUrl = imageUrl;
  77.   }
  78.  
  79.   /** @returns {string} */
  80.   get title() {
  81.     return this._title.title;
  82.   }
  83.  
  84.   /** @returns {string} */
  85.   get content() {
  86.     return this._content.content;
  87.   }
  88.  
  89.   /** @returns {string} */
  90.   get imageUrl() {
  91.     return this._imageUrl.url;
  92.   }
  93.  
  94.   toString() {
  95.     return `${this.title}\n${this.content}\n${this.imageUrl}`;
  96.   }
  97. }
  98.  
  99. const post = new Post(
  100.   new Title('This is a title.'),
  101.   new Content('This is a post.'),
  102.   new Url('http://example.com'));
  103.  
  104. console.log(post.toString());
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement