Tech Junkie Blog - Real World Tutorials, Happy Coding!: AngularJS SPA: Building The Bank Application JavaScript Objects (Business Entities)

Wednesday, January 9, 2019

AngularJS SPA: Building The Bank Application JavaScript Objects (Business Entities)

Up until this point all we did was take care of the plumbing, MongoDB for the database, AngularJS as the application framework, expressJS for hosting, and Heroku as deployment infrastructure in the cloud. Whew! It feels like I am spitting out development hastags and buzzwords.  But, you know what they always say "it takes a village to build a SPA application".  Well they didn't say that, but they should! Who are they anyways?  The software engineer gods?  Or god forbid the mythical "full stack developers!!  Fear them the full stack developers!  But I don't know who they are, you ask.  Well they are just awesome! God says.  They are 10x!  Wow 10x, you said to yourself.  They must be good!  Hahaha  I just love the buzzwords.  It's entertaining.  I would never say I am a full stack developer.  I am just a developer who knows a lot of stuff.

In this post we are going to take a step back and start working on the actual application and take the plumbing out of the equation for a while.

As with any application at the center of it all is the question.  What does the application do?
Since our application is banking application, we will create objects that are in the banking domain.  This is called a domain driven design.  We are not going to follow the domain driven design (DDD) to a T, but we will follow the spirit of it.



First things first, we need a bank.  Follow the steps below to create the bank object.

  1. Open the "ACMEBank" application with your favorite IDE
  2. Add the file bank.js to the models folder 











3. Add an IFFE to the file

(function () {
}());

4. Now let's create the bank object

(function () {
    function Bank(name, user) {
        this.Name = name;
        this.User= user;
    }
}());

You might be wondering why we created the Bank object with a function.  The reason we did that is because we basically created a constructor that we initiate with constructor arguments. The object has two properties, the name of the bank and the user that is accessing the application. Now I could create another file to create a user object but since it's such a simple object I am going to put it in the same file as the bank.js file. The User object just contains the name of the user and the accounts that belongs to the user.

Here is the code to create the User object

(function () {
    function User(name, accounts) {
        this.Name = name;
        this.Accounts = accounts;
    }

    function Bank(name, user) {
        this.Name = name;
        this.User= user;
    }
}());

5. Now it's time to create the account object, create a file call account.js in the models folder.
(function () {
    function Account(balance, type) {
        this.balance = balance;
        this.type = type;
    }

    Account.prototype.deposit = function (d) {

        this.balance = this.balance + d;
        return this.balance;
    }

    Account.prototype.withdrawal = function (w) {
        this.balance = this.balance - w;
        return this.balance;
    }
}());

The account object basically has the balance, and type properties as well as the deposit and withdrawal method in it's prototype. If you need more information on JavaScript prototypes you visit this post.

Now lets say we have another kind of account class which is the Premium (high earners) account class this class can make withdrawal, and deposit like the regular account.  But it can do more like transfer to another account.  Also it pays a 5% bonus on the balance every time he/she makes a deposit or on account creation.  Even though this is probably way too generous, I just wanted to simulate a business rule that you might encounter in real life.  Therefore, programmatically we want to inherit from the base class which in this case is the Account class. This is how we would inherit from the Account class and build a Premium class.  First let's create the "inherits" function which will inherit the prototype object from the Account class to the Premium class.


        function inherits(baseClass, childClass) {
            childClass.prototype = Object.create(baseClass.prototype);
        }

As you can see its not really a real inheritance, it's more of a simulation of an inheritance.  We cloned or copy the prototype object of the Account class, which in this case is the base class.  Think of the base class the original copy, and Premium class the clone.  But the clone can have it's own methods after it has been cloned.  Kind of like the T1000 in Terminator.

Now let's create the Premium class

        function Premium(balance,type) {
            this.balance = balance + (balance*.05);
            this.type = type;
        }

As you can see the T1000, I mean the Premium class has it's own way of figuring out the balance with a 5% bonus.

Now let's call the "inherits" function to inherit from the Account class.

        inherits(Account, Premium);

Now that we inherited from the Account class we are going to add the "transfer" function that is exclusive to the Premium class

        Premium.prototype.transfer = function (from, to, amount) {
            from.balance -= amount;
            to.balance += amount;
        }

In its current state the deposit function does not add the 5% to the deposit because it's using the Account's inherited functions.  To get the correct balance for the Premium class we can override the deposit and function.  Like this

        Premium.prototype.deposit = function (d) {
            this.balance = this.balance + d;
            this.balance = this.balance + (this.balance * .05);
            return this.balance;

        }

Here is the full code for the account.js file

(function () {
    function Account(balance, type) {
        this.balance = balance;
        this.type = type;
    }

    Account.prototype.deposit = function (d) {

        this.balance = this.balance + d;
        return this.balance;
    }

    Account.prototype.withdrawal = function (w) {
        this.balance = this.balance - w;
        return this.balance;
    }


    function inherits(baseClass, childClass) {
        childClass.prototype = Object.create(baseClass.prototype);
    }

    function Premium(balance, type) {
        this.balance = balance + (balance * .05);
        this.type = type;
    }


    inherits(Account, Premium);

    Premium.prototype.transfer = function (from, to, amount) {
        from.balance -= amount;
        to.balance += amount;
        from.rebalance();
        to.rebalance();
    }

    Premium.prototype.deposit = function (d) {
        this.balance = this.balance + d;
        this.balance = this.balance + (this.balance * .05);
        return this.balance;

    }
    Premium.prototype.rebalance = function()
    {
       this.balance +=  this.balance * .05;
    }
}());

Note: I've added the rebalance prototype method to the Premium object as another way to resolve the %5 bonus for the Premium deposits. You can learn more about JavaScript inheritance in this post.

Your models folder should look like this













Similar Posts:

Previous: AngularJS SPA: Install RoboMongo GUI for MongoDB

56 comments:

  1. It’s amazing how interesting it is, My first visit made me very happy. Thanks bank al habib car loan | best mutual funds in pakistan

    ReplyDelete
  2. I think a good place to start for a newcomer is with a Swedish Massage and a facial. These are still the most favorite spa treatments because people love them. Although there are many wonderful treatments on most spa's menus, such as hot stone massage, Ayruvedic treatments or even body scrubs and wraps, I would not recommend them for the first time spa-goer.full body massage

    ReplyDelete
  3. Thank you for posting this, this is very powerful! sir RNkhabri

    ReplyDelete
  4. Oferecemos os melhores serviços para seguidores, curtidas, comentários e visualizações no Instagram. Os serviços são entregues de forma rápida, segura e por um preço honesto e barato.
    Todos os serviços são iniciados de forma automática e você pode fazer um teste grátis de seguidores, curtidas e visualizações no Instagram.

    O Go Followers surgiu em 2015 e durante alguns anos foi o melhor e maior site para comprar seguidores, curtidas e comentários no instagram. Com o passar dos anos evoluímos e em 2021 lançamos um novo site simples e intuitivo para aumentar a experiência dos mais de 150.000 clientes atendidos.

    Nossa ferramenta envia seguidores brasileiros reais e ativos em sua grande maioria para qualquer perfil do Instagram. Escolha o melhor pacote para comprar seguidores instagram de alta qualidade. Você poderá escolher alguns pacotes como seguidores com curtidas, seguidores masculinos, seguidores femininos e seguidores automáticos.
    Todos os pedidos são feitos de forma automática e iniciam em poucos minutos após a compra, tá esperando o que?

    ReplyDelete
  5. Garuda999 adalah sebuah agen casino online yang merupakan mitra salah satu bandar judi online24jam internasional terbesar di Asia, SBobet, yang berpusat di Filipina. Sebagai salah satu mitra penyedia layanan judi online terbesar, tentunya kami juga berkomitmen untuk memberikan layanan terbaik bagi pengguna kami, yaitu penggemar judi online Indonesia. judi slot game, slot online nexus, slot online casino, slot online 88, slot online idn, bandar togel idn, judi bola pulsa, casino online terbesar di dunia, bandar togel pasaran terbaik, judi bola 777, situs judi bola yang ada promo bonus 100, judi bola 828, casino online game, judi bola depo pulsa, situs judi bola freebet, situs judi online poker yang banyak bonus, judi online live, judi poker deposit pakai pulsa 5000 Dengan adanya aturan yang berlaku di Indonesia, kami menyadari jika banyak penggemar judi online di Indonesia, yang kesulitan untuk mendapatkan layanan yang berkualitas. Sehingga untuk itulah kami, Garuda 999 hadir sebagai agen casino yang terpercaya, untuk melayani penggemar judi online di Indonesia, tanpa bertentangan dengan aturan yang berlaku. Karena sebagai mitra yang mematuhi aturan, kami beroperasi dari Manila, Filipina, sebagaimana mitra induk kami. Dengan demkian penggemar judi online di Indonesia, dapat dengan mudah mengakses layanan judi online, yang kami sediakan dan merasakan kesenangan bermain judi online dengan aman dan nyaman, selayaknya bermain pada casino online bertaraf internasional. judi bola aman, Judi Slot terlengkap, master judi bola 99, qq slot online freebet,judi online poker sampoerna, slot online indonesia terpercaya, slot online game, situs judi bola eropa, bandar togel kamboja, judi bola 168, slot online judi, peraturan judi bola 90 menit, 9 poker, casino online paypal, judi bola deposit pulsa, judi bola adalah casino online di indonesia, bandar togel tertua dan aman, casino online malaysia, judi bola mix parlay, bandar, togel onlen, casino online terbaru. Sebagai agen casino online mitra dari SBobet, yang merupakan salah satu agen bola Euro2021 terbesar di Asia, tentunya Garuda 999 juga membuka peluang bagi penggemar taruhan olah raga khususnya sepak bola, di tanah air, untuk ikut meramaikan even sepak bola dunia tersebut. Dengan didukung oleh sistem sports book handal yang disediakan oleh SBobet, penggemar taruhan sepak bola di Indonesia - Judi Online, tidak perlu khawatir untuk ketinggalan bertaruh pada even besar tersebut. Karena sistem sports book yang kami adopsi dari mitra induk kami, merupakan salah satu yang terbaik di dunia, yang dapat melayani taruhan sesuai jadwal pertandingan pada Euro 2021 secara real time - Judi Slot.

    ReplyDelete
  6. Ob Schmutz, hartnäckiger Belag, Schimmel, Vogelkot, Bakterien, Dreck, Staub oder unangenehme Gerüche, bei unserer Gebäudereinigung Hannover erwartet Sie ein glänzendes Ergebnis. Die Firma Immoclean reinigt Gebäude unterschiedlichster Art wie Schulen, Kindergarten, Arztpraxis, Altersheim, Museum, Disko, Hallen, Krankenhaus, Hotel, Baustelle, Restaurant, Kaufhaus, Supermarkt - Unterhaltungsreinigung Hannover.

    Vertrauen Sie dabei unserer Erfahrung, den vielen Referenzen und einer Kundenzufriedenheitsgarantie. Zuverlässigkeit und Qualität sowie eine absolut hygienische Reinigung können wir Dank unseren geschulten und mit modernstem Reinigungsequipment ausgestatteten Mitarbeitern gewährleisten - Broreinigung Hannover. In einer umfassenden und persönlichen Beratung erstellen wir sowohl für Klein- als auch Großkunden einen persönlichen Reinigungsplan ganz nach Ihren Wünschen. Bei Immoclean aus Hannover, der Nummer 1 unter den Reinigungsdiensten, Gebudereinigung hannover ist Ihre Firma oder Unternehmen in guten Händen. Vereinbaren Sie noch heute einen Termin mit unserem Reinigungsunternehmen, wir freuen sich auf Sie - Praxisreinigung Hannover!

    ReplyDelete
  7. In the event that you are a user of Brother printer at your home or workspace and looking for the right direction to interface it to Wifi then today you have arrived at the opportune spot. Connect brother printer mfc l2750Dw to wifi We, Tech Support Expert is the best outsider specialized network that is master in tackling all your printer issues. Our network has a group of multi-gifted and talented specialized experts who give lasting setup and extraordinary exhortation users. In this blog area, we are here with the answer for brother Printer not Connecting to WiFi issue

    ReplyDelete
  8. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up
    Regards : Plumber in clapham

    ReplyDelete
  9. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. Gebäudereinigung Hardegsen

    ReplyDelete
  10. I am able to provides you with the objective In this article understand the best way to practice it the right way. Understand in addition to generate anything beneficial. glock 35 mos

    ReplyDelete
  11. Archipelago Learning ialah agen bola terpercaya yang mempunyai daftar bandar bola resmi, pelayanan situs terbaik dan selalu memberikan keuntungan promo terbesar di ...

    ReplyDelete
  12. DAFTAR 6 situs judi online TERPERCAYA 2021 · 1. Slot Online Pragmatic Play · 2. Slot Online Joker123 · 3. Slot Online Playtech · 4. Slot Online PGSoft · 5. Slot ...

    ReplyDelete
  13. There are in any case, a few kinds of building projects that may likewise be dependent upon different sorts of legal necessities and assents so you should ensure that you remember this.
    Tree Cutting Pearland

    ReplyDelete
  14. Eliminate the cleaning agent from your skin with the lukewarm water in your plastic bowl. HydraPeel

    ReplyDelete
  15. I am so grateful for your article. Much thanks again.
    San Bernardino tree removal team

    ReplyDelete
  16. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think. Chris

    ReplyDelete
  17. The Indoor Tanning Association tell human beings approximately the blessings of tanning, such as how it's far used to therapy situations like Acne and Psoriasis.Boca tanning

    ReplyDelete
  18. ESD Tray & Anti static PP Tray material: Injected PP material Size: customized Surface resistance:10^3-9 Color: Black More products Details Anti static Paper box Main material: PE foam+ paper box Size: customized Surface resistance: 10^3-9 Color: Black More products Details Anti static Corrugated box. Visit our website anti static tray to learn more.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. A rural styled room can be organized accordingly, a nation style, a contemporary style, and so on8500 burton way

    ReplyDelete
  21. It may seem simple yet it is often times overlooked. When it comes to choosing the right Internet hosting provider for their websites, the majority of business owners or companies know very little ab... https://onohosting.com/

    ReplyDelete
  22. Real estate returns additionally show a high relationship with expansion.figueroa terrace

    ReplyDelete
  23. Great thanks for sharing this article post. Really thank you! Really Cool.real estate developer

    ReplyDelete
  24. If you have arthritis you might want to turn to massage to address both your pain and the stiffness of your condition and your general well-being. check more info about spa center

    ReplyDelete
  25. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. https://thebedokspa.sitey.me/

    ReplyDelete
  26. Thanks so much for this information. I have to let you know I concur on several of the points you make here and others may require some further review, but I can see your viewpoint. yue yuan spa singapore

    ReplyDelete
  27. Thanks for this great post, i find it very interesting and very well thought out and put together. I look forward to reading your work in the future. Glasreinigung Einbeck

    ReplyDelete
  28. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find so many useful info here in the post, we need work out more techniques in this regard, thanks for sharing. Massage Spa Center

    ReplyDelete
  29. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. singapore best spa 9

    ReplyDelete
  30. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. yi spa in singapore

    ReplyDelete
  31. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work! massage service

    ReplyDelete
  32. Thank you very much for this useful article. I like it. massage spa singapore

    ReplyDelete
  33. buying yt views YouTube network marketing strategies have proven to be efficient of late. Now more than ever, network marketers are using the internet to connect with people all over the world. Utilizing the world wide web has quickly become one of the most popular and efficient lead generation strategies.

    ReplyDelete
  34. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work... massage therapist singapore massage

    ReplyDelete
  35. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. https://medium.com/@theangelwillis/where-to-get-a-massage-in-singapore-9cc1bd59818a

    ReplyDelete
  36. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. https://site-7051161-6813-5430.mystrikingly.com

    ReplyDelete
  37. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. 24 hour spa

    ReplyDelete
  38. experienced administrators, professional and managers are required, besides the major experts of nurses, doctors and frontline authorities. managing aggressive behavior for healthcare professionals

    ReplyDelete
  39. it is an excellent way for Western women to overcome numerous issues and awaken their own senses. It comes as no surprise that sensual massages are often part of sexual therapy sessions since they have proven to help female patients overcome various sexual problems. Remedial Massage

    ReplyDelete
  40. We recently covered the importance of professional website design as well as how a website design company can help you benefit from a customized website. A professional website design company can assist you in leveraging the power of the Internet in a number of ways. Website Design Company Dubai

    ReplyDelete
  41. As a matter of fact, it will build your protective cells for neutralizing viruses that may cause cancer. Moreover, a strong immune system plays a vital role in keeping you in good shape. 강남 출장안마

    ReplyDelete
  42. There are a lot of commercial security alarm companies out there, and it can be tough to know which one to choose. commercial security alarm companies

    ReplyDelete
  43. A chiropractor clinic is one of the most popular types of healthcare facilities. They treat many health conditions and work closely with other health professionals to achieve the best possible results for their patients. Chiropractors work in private practice, multi-disciplinary clinics, family health teams, hospitals and even in the patient's home. They can provide onsite support for large corporations. Physicians at chiropractors' clinics use a combination of manual techniques, stretching, and sustained pressure to achieve the desired results. For more information, visit the chiropractors website.

    ReplyDelete
  44. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. https://singapore-massage.mystrikingly.com/

    ReplyDelete
  45. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. full body massage near me

    ReplyDelete
  46. Neco expo runz 2023: in case you are a candidate who has been asking such a lot of questions about the Neco expo government 2023, Neco expo WhatsApp institution link, “how to get waec runs for 2023? Then you are Welcome to our web page.

    ReplyDelete
  47. Thank You Sir This is Very Informative, thank you sir for providing this information to us. Singh

    ReplyDelete
  48. Maximize your online potential with our dynamic digital marketing solutions. From SEO to PPC, social media to content creation, we have the strategies to elevate your brand. Visit quadrobits for more information.

    ReplyDelete
  49. At GO by Fabrifest, we take pride in offering a diverse range of men's shirts that blend quality, comfort, and style effortlessly. From classic dress shirts for those important occasions to contemporary casual options, our collection caters to every facet of your personality. Find more information katua for men. Find the perfect fit and fabric that suits you best, and experience the epitome of elegance in every wear. Make a lasting impression with our shirts, where refined elegance meets your unique charm.

    ReplyDelete
  50. The information covered in your article offers a thorough understanding of the subject. If you're seeking part-time employment, please click the provided link.zoopup!

    ReplyDelete
  51. "Bangladesh Scenic Tours" invites you to delve deeper into the soul-stirring landscapes and cultural mosaic of Tour Operator in Bangladesh. With meticulous planning and local expertise, they offer an array of experiences, from historical landmarks to natural wonders. Let each moment unfold, creating a tapestry of memories in the heart of this enchanting destination.

    ReplyDelete

Search This Blog